29. Custom Hooks
Reusing Component Logic
We know how to reuse UI: we extract it into a Component. But what if we want to reuse logic? If you have two different components that both need to fetch data from an API, or track window resize events, or manage a complex counter, you shouldn't duplicate that code. Custom Hooks allow you to extract stateful logic into reusable JavaScript functions.
What is a Custom Hook?
A Custom Hook is simply a JavaScript function whose name starts with use (e.g., useCounter, useFetch) and that calls other React Hooks (like useState or useEffect) inside of it.
Using the Custom Hook
Now, any component in your application can use this complex counting logic with a single line of code. The UI remains clean and focused entirely on presentation.
Are Custom Hooks Shared State?
No. Custom Hooks share stateful logic, not the state itself. If you use the useCounter hook in Component A, and also use it in Component B, they will each get a completely independent, isolated count variable. Clicking the button in Component A will not affect Component B.
Knowledge Check
Ready to test your understanding of 29. Custom Hooks?