We need custom hooks, where we have a function component, which uses built-in hooks, like useState or useEffect, and has redundant code in it. Since we cannot use built-in hooks with functions, we create custom hooks to use these built-in hooks to be used in the function component [or a custom hook, now]. It is basically to reduce redundant code where we are dependent upon built-in hooks.
Custom hooks are functions where we can outsource stateful logic into re-usable functions. But unlike "regular functions", custom hooks can use other React hooks and React state.
The naming convention is to be followed while creating custom hooks.
Store all custom hooks in a hooks/ folder, at root level in /src
The file name for the custom hook must be use-<hook_name>.js
The hook function should be named in camelCase, like useHookName
Import the hook like we did other default built-in hooks.
When calling a custom hook, the state of that custom hook is then tied to the functional component in which we call that custom hook. Every component in which we use our custom hook, a fresh set of state is bound to each component, which is different from the other components.
We need to return something from our custom hooks. It can be a variable of primitive data type, can be an array, an object, etc.
Example
Consider the following useCounter() custom hook example:
The above logic for the custom hook only solves the issue for the ForwardCounter component. To have the same custom hook count backwards, i.e, for the BackwardCounter, we need to configure our custom hook. For this, we will use a flag, i.e, a boolean, to check if we are counting forwards, for the ForwardCounter component, or backwards for the BackwardCounter component.
We set a boolean flag forward which is set to true by default. This value is checked in the useEffect() where we update the state of the counter, whether we need to increment or decrement the counter.
The ForwardCounter component remains the same, but here is the updated BackwardCounter component.