Create your own React Hook.
Updated: Jul 27, 2020
The biggest hurdle developers face when using React functional components is the absence of lifecycle components. To remedy this, React introduced “Hooks” in React 16.
Hooks revolutionized the way React code is written. Now writing functional components using hooks is the standard. The most widely used hooks are useState and useEffect, which are used to bring the functionality of state and lifecycle components into functional components respectively.
React also introduced the concept of “Custom Hooks” in React 16. Custom hooks help to reduce redundant logic repeated in multiple components. The name of a custom hook should be prefixed with the word “use”. Custom hooks became very popular as soon as it’s launched. Now, most major third-party libraries expose their features using custom hooks. Most notable ones are “useHistory” custom hook by React Router & “useStyles” custom hook by Material UI.
Let us explore Custom Hooks with a simple example.
A hook to implement the functionality of a counter. Let us call the hook ‘useCounter’. The hook should increase the value of the counter by 1 when the increment is clicked and decrease the value of the counter by 1 when decrement is clicked. In our hook let us use useState hook to save and maintain count value.
In the example, we created a function, named it with the word “use” as a prefix, and returned the calculated value, voila! a custom hook is ready. In useCounter, we use useState hook to implement the counter, the count and the increment, decrement functions are returned. They can be accessed by the function using the hook. Let us use this hook in a functional component.
Writing a Custom hook is as simple as that. Now let us add more features to useCounter. Let’s use the useEffect hook within useCounter to set a max limit on the counter and reset the counter when the limit is reached. Let us get the max limit from an API call.
This hook can now be imported and used in any functional component in the application.
There is no limit to what can be achieved using Custom hooks. More complex custom hooks can be made using other hooks like useMemo, useRef, useReducer, etc.