- A custom Hook is a JavaScript function whose name starts with “use” and that calls other Hooks.
- Custom Hooks let you extract state logic into reusable and composable units.
Here’s an example of a custom Hook that manages the value of a text input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import React, { useState } from 'react'; import ReactDOM from 'react-dom/client'; function useHits() { const [hits, setHits] = useState(0); const handleHits = () => { setHits(hit => hit + 1); }; return [hits, handleHits]; } function App() { const [hits, handleHits] = useHits(); return ( <div> <p>Hits: {hits}</p> <button onClick={handleHits}>Hit Me</button> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
In this example, the useHits custom Hook abstracts the state management and event handling for counting hits.
The APP component can then use the useHits Hook to manage the number of hits, without having to deal with the details of state management and event handling.
in this way, we can reuse the logic across multiple components, making your code more readable and maintainable.