How to Fix React Custom Hook State Not Shared Between Components
In this fix, you'll learn why two components using the same custom hook have different state, why this matters for shared logic in form validation or data fetching, and how this affects reusable hook libraries in {React.
Every call to a custom hook creates its own independent state. Hooks are not singletons โ each component instance that calls the hook gets its own copy of the hook's internal useState and useEffect calls.
The Problem
The following code demonstrates the typical mistake:
function useCounter() {
const [count, setCount] = useState(0);
return { count, increment: () => setCount(c => c + 1) };
}
function ComponentA() { const { count } = useCounter(); return <p>A: {count}</p>; }
function ComponentB() { const { count } = useCounter(); return <p>B: {count}</p>; }
// A: 0, B: 0 โ independent counters
The Fix
Here is the corrected version:
// To share state, lift it to a common ancestor:
function App() {
const [count, setCount] = useState(0);
return (
<>
<ComponentA count={count} increment={() => setCount(c => c + 1)} />
<ComponentB count={count} />
</>
);
}
// Both components display the same count
Prevention
- Custom hooks create isolated state per call โ each component instance gets its own state.
- To share state between components, lift state to a common ancestor and pass down via props.
- Use React Context inside a custom hook for shared state without prop drilling.
- For global shared state, consider Zustand, Jotai, or React Context.
- Document custom hooks clearly โ indicate whether they create local state or read shared context.
Common Mistakes with custom hook state
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro