React Context Re-render Error Fix
In this tutorial, you'll learn about React Context Re. We cover key concepts, practical examples, and best practices.
The Problem
All context consumers re-render when a single value in the context changes, even if they only use the unchanged part.
Wrong
const AppContext = React.createContext()
function App() {
const [user, setUser] = useState(null)
const [theme, setTheme] = useState('light')
return (
<AppContext.Provider value={{ user, theme, setUser, setTheme }}>
<UserProfile />
<ThemeToggle />
</AppContext.Provider>
)
}
Both UserProfile and ThemeToggle re-render when either user or theme changes.
Right
Split into separate contexts:
const UserContext = React.createContext()
const ThemeContext = React.createContext()
function App() {
const [user, setUser] = useState(null)
const [theme, setTheme] = useState('light')
return (
<UserContext.Provider value={{ user, setUser }}>
<ThemeContext.Provider value={{ theme, setTheme }}>
<UserProfile />
<ThemeToggle />
</ThemeContext.Provider>
</UserContext.Provider>
)
}
function UserProfile() {
const { user } = useContext(UserContext)
return <div>{user?.name}</div>
}
function ThemeToggle() {
const { theme, setTheme } = useContext(ThemeContext)
return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
{theme}
</button>
}
Expected output: changing theme does not re-render UserProfile.
Prevention
- Split large contexts into smaller, focused contexts
- Use
useMemofor context values to prevent unnecessary re-renders - Consider state management libraries like Zustand for complex state
Common Mistakes with context re render
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
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