javascript / beginner
Snippet
Extracting Reusable State into a Custom Hook Pattern
The Custom Hook design pattern extracts stateful component logic into reusable functions starting with the 'use' prefix. This separation of concerns allows multiple components to share state behavior without duplicating code or modifying component hierarchies.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { useState } from 'react';function useCounter(initialValue = 0) {const [count, setCount] = useState(initialValue);const increment = () => setCount(prev => prev + 1);const reset = () => setCount(initialValue);return { count, increment, reset };}export default useCounter;
react
Breakdown
1
function useCounter(initialValue = 0) {
Defines a custom hook following standard naming conventions with an initial parameter.
2
const [count, setCount] = useState(initialValue);
Maintains encapsulated numeric state within the custom hook instance.
3
const increment = () => setCount(prev => prev + 1);
Encapsulates state mutation logic within a reusable helper function.
4
return { count, increment, reset };
Returns state values and updater functions bundled inside a plain object.