Custom Hook
Sridhar Raj P
?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ?? | JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver
Custom Hooks are a powerful feature introduced in React 16.8 that allow developers to extract and reuse stateful logic across multiple components, promoting cleaner and more maintainable code.
What Are Custom Hooks?
A Custom Hook is essentially a JavaScript function whose name starts with "use" and that may call other Hooks. This naming convention is crucial because it enables React to identify these functions as Hooks, ensuring that the rules of Hooks are enforced.
Key Characteristics:
Creating a Custom Hook: Example
Let's create a simple custom Hook called useCounter, which manages a counter state with increment and decrement functionalities.
// useCounter.js
import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(prevCount => prevCount + 1);
const decrement = () => setCount(prevCount => prevCount - 1);
return { count, increment, decrement };
}
export default useCounter;
In this Hook:
2. Utilize the Custom Hook in a Component:
// CounterComponent.js
import React from 'react';
import useCounter from './useCounter';
function CounterComponent() {
const { count, increment, decrement } = useCounter(10); // Starting count at 10
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default CounterComponent;
Here:
Benefits of Using Custom Hooks