Custom react hooks using useEffect

Here is the working example.

Ever wonder how to create a custom react hook using useEffect?

In the following steps we will discuss more about this subject.

First, let’s start by creating our custom hook:

import { useState, useEffect } from "react";

const useCounterEffect = () => {
  const [counter, setCounter] = useState(0);
  const [maxValue, setMaxValue] = useState(0);
  useEffect(() => {
    if (counter < maxValue) setCounter(counter + 1);

    return () => {};
  }, [counter, maxValue]);
  return [counter, setMaxValue];
};

export default useCounterEffect;

In the code above we are creating an effect which will be called when either counter or maxValue will change. We are wrapping this effect in a function which will then expose setMaxValue. This setMaxValue will then be used whenever we want to increase our counter.

Conclusion

Creating a custom hook does not imply any special javascript constructs. It’s as simple as defining a function and then return those properties, however be aware these hooks can only be called only from react function components.

Get The Best Of All Posts Delivered To Your Inbox

Subscribe to our newsletter and stay updated.