Custom Hooks in React
Learn how to create Custom Hooks to reuse stateful logic across React components and organize your application code.
1. What Are Custom Hooks?
A Custom Hook is a JavaScript function that allows developers to reuse logic involving React Hooks across multiple functional components.
For example, if multiple components need to manage a counter, track a window size, or handle form input, that logic can be placed inside a Custom Hook and reused.
use,
such as useCounter or useWindowWidth.
2. Why Do We Use Custom Hooks?
Custom Hooks help separate reusable logic from component UI. Instead of writing the same state management logic repeatedly, developers can define it once and reuse it.
- Reuse stateful logic across components.
- Reduce repeated code.
- Improve code readability and organization.
- Keep components focused on displaying the UI.
- Make shared logic easier to maintain.
3. How Custom Hooks Work
A component calls a Custom Hook just like it calls a built-in Hook. The Custom Hook can use built-in Hooks and return the values or functions the component needs.
4. Example: Creating a Custom Counter Hook
In this example, we create a Custom Hook called
useCounter. It manages a counter value
and provides a function to increase it.
Example Code: useCounter.js
import { useState } from "react";
function useCounter() {
const [count, setCount] = useState(0);
function increaseCount() {
setCount(previousCount =>
previousCount + 1
);
}
return {
count,
increaseCount
};
}
export default useCounter;
Example Code: App.jsx
import useCounter from "./useCounter";
function App() {
const { count, increaseCount } = useCounter();
return (
<div>
<h2>Custom Hook Example</h2>
<p>Count: {count}</p>
<button onClick={increaseCount}>
Increase Count
</button>
</div>
);
}
export default App;
Expected Output
Custom Hook Example
Initially: Count: 0
After one click: Count: 1
After two clicks: Count: 2
useCounter Hook manages the count and
returns the current value and the increase function.
The App component uses those returned values to display
and update the counter.
5. Reusing a Custom Hook in Multiple Components
The same Custom Hook can be called from different components. Each component maintains its own independent counter state.
Example Code: Counter.jsx
import useCounter from "./useCounter";
function Counter() {
const { count, increaseCount } = useCounter();
return (
<div>
<h3>Counter: {count}</h3>
<button onClick={increaseCount}>
Increase
</button>
</div>
);
}
export default Counter;
Example Code: App.jsx
import Counter from "./Counter";
function App() {
return (
<div>
<h2>Multiple Counters</h2>
<Counter />
<Counter />
</div>
);
}
export default App;
Expected Output
Multiple Counters
Counter: 0 [Increase]
Counter: 0 [Increase]
Clicking Increase in the first counter changes only the first counter's value. The second counter keeps its own value.
useCounter()
creates independent state for that component.
6. Example: Creating a Custom Input Hook
We can create a Custom Hook to manage the value of an input field and reuse the same logic in forms.
Example Code: useInput.js
import { useState } from "react";
function useInput(initialValue = "") {
const [value, setValue] = useState(initialValue);
function handleChange(event) {
setValue(event.target.value);
}
return {
value,
onChange: handleChange
};
}
export default useInput;
Example Code: App.jsx
import useInput from "./useInput";
function App() {
const name = useInput("");
const course = useInput("");
return (
<div>
<h2>Student Registration</h2>
<input
placeholder="Enter name"
{...name}
/>
<br /><br />
<input
placeholder="Enter course"
{...course}
/>
<p>Name: {name.value}</p>
<p>Course: {course.value}</p>
</div>
);
}
export default App;
Expected Output
Student Registration
[ Enter name ]
[ Enter course ]
After entering Samadhan and React:
Name: SamadhanCourse: React
useInput Hook manages an input value and
its change handler. The spread syntax passes the returned
value and onChange handler to each input field.
7. Rules for Creating Custom Hooks
-
Start the Custom Hook name with
use. - Call built-in Hooks only at the top level of the Custom Hook.
- Do not call Hooks inside loops, conditions, or nested functions.
- Call Custom Hooks from React function components or other Custom Hooks.
- Return the values or functions needed by the component using the Hook.
8. Practice Tasks
Complete the following exercises:
- Create a Custom Hook called useCounter with an increase function.
- Add decrease and reset functions to useCounter.
- Create a Custom Hook called useInput to manage text input values.
- Use the same Custom Hook in two separate components.
- Create a Custom Hook that tracks a boolean value and toggles it.
- Explain the difference between sharing logic and sharing state.