Creating own reusable Custom Hook to be used by multiple functional components.
Hooks are nothing, but reusable methods. Hooks are nothing, but reusable methods with a state. Hooks are nothing, but reusable methods with a state, which helps in extracting complex component logic into methods.
Please follow this blog for basic details on hooks : https://vivek-sinless.medium.com/hookup-of-hooks-with-react-2749d9c2e4b
Traditionally in React, we’ve two popular ways to share stateful logic between components: render props and higher-order components.
Generally the name of the hooks starts from ‘use’, and it is advised to use the same naming convention, so that tools like eslint can find out if there’s any violations made in hooks.
In this practical example, say that we manage a count of the total number of 2 wheeler, and 4 wheeler vehicles.
In this case we will create two functional components — one for 2 wheeler , and other for 4 wheeler vehicle, and we will have separate states for both the 2 wheeler and 4 wheeler components, which is complex. Hence we should have a solution, where we can reuse the code easily, that is where a custom Hook can help.
This solution is using a custom Hook :
index.js
import { StrictMode } from “react”;import ReactDOM from “react-dom”;import App from “./App”;const rootElement = document.getElementById(“root”);ReactDOM.render( <StrictMode> <App /> </StrictMode>, rootElement);
App.js
import React from ‘react’;import FourWheeler from ‘./FourWheeler’;import TwoWheeler from ‘./TwoWheeler’;function App() { return ( <div> <TwoWheeler typeOfVehicle=”Bike”/> <FourWheeler typeOfVehicle=”Car”/> </div> );}export default App;
We just call the two functional components here passing the type of vehicle as props.
TwoWheeler.js
import React from ‘react’;import useCountHook from ‘./useCountHook’;export default function TwoWheeler(props) {const countHook = useCountHook(); return ( <div> <h1>{props.typeOfVehicle}:{orderHook.orderCount.count}</h1> <button type=’button’ onClick= {countHook.changeOrderCount}>Increment</button> </div> )}
We are not maintaining the state in the component itself . We will use hook to manage the state for both the component.
FourWheeler.js
import React from ‘react’;import useCountHook from ‘./useCountHook’;export default function FourWheeler(props) {const countHook = useCountHook(); return ( <div> <h1>{props.typeOfVehicle}:{orderHook.orderCount.count}</h1> <button type=’button’ onClick= {countHook.changeOrderCount}>Increment</button> </div> )}
We have created a custom hook below which takes care of the common functionality of both the components. Hooks itself is maintaining the state. If we did not use a custom hook, we would have to either write the same logic in both the TwoWheeler and FourWheeler components, or we would create a higher order component. It is complex to manage a higher order component.
1.) It’s hard to reuse stateful logic between components
2.) Complex components become hard to understand
3.) Classes confuse both people and machines
useCountHook.js (Custom hook)
import { useState } from ‘react’;function useCountHook() { const [orderCount, setOrderCount] = useState({ count: 0 }); const changeOrderCount = () => { setOrderCount({ count: orderCount.count + 1 }) } return { orderCount, changeOrderCount };}export default useCountHook;
This is how the UI looks like :
The only confusing part here is with the two components sharing same hook logic to maintain a state. Do not worry, both the functional component will have its own state. Remember, we can have multiple useState hook in a component. Similarly, React will maintain separate state for components.
Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.
How does a custom Hook get isolated state? Each call to a Hook gets isolated state. Because we call useCountHook directly, from React’s point of view our component just calls useState . And as we learned earlier, we can call useState and useEffect many times in one component, and they will be completely independent.
Please reach out to me for any queries or any freelancing work.