Nearby lessons
26 of 44🪝 ReactJS – Custom Hooks
📌 What are Custom Hooks?
What are Custom Hooks in React?
Custom Hooks are reusable functions that allow you to extract component logic into a separate function. When multiple components need the same logic, we can reuse it by creating a Custom Hook.
Custom Hooks follow the naming convention of starting with use,
such as useCounter.
📌 Why Custom Hooks?
- Custom Hooks help you reuse logic across multiple components.
- They make your code cleaner and more modular.
- They always start with the word
use. - They can use built-in hooks like
useState,useEffect, etc.
⚙️ Example – useCounter Hook
Below is an example of a Custom Hook called useCounter.
It provides a counter value along with Increment and Decrement functions.
React Playground
import React from 'react'; import useCounter from './useCounter.jsx'; function App() { const [count, Increment, Decrement] = useCounter(); return ( <> <h1>Learning Custom Hook</h1> <h2>{count}</h2> <button onClick={Increment}>Increment</button> <button onClick={Decrement}>Decrement</button> </> ); } export default App;
🧩 Rules of Custom Hooks
- Always start the function name with
use(e.g.,useFetch,useAuth). - Custom Hooks can call other hooks (
useState,useEffect, etc.). - They follow the same Rules of Hooks: only call hooks at the top level, and only inside React functions.
🔄 Benefits of Custom Hooks
- Code reusability across multiple components.
- Keeps components simple and focused on UI.
- Makes testing easier by isolating logic.
- Improves maintainability and scalability.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4
Keep Going!React - React Router Introduction