β Why React Re-Renders Happen
In React, any time state or props change, a component re-renders. Thatβs good β but not always necessary.
Here are common culprits:
Overusing useState in deeply nested components
Passing down too many props (especially objects/functions)
Not memoizing expensive calculations or callbacks
Updating global state on every small action
π Real Example: Over-Reactive State
function App() { const [count, setCount] = useState(0); return ( <div> <Header /> <Main count={count} /> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } In this setup, every time count changes, both Header and Main re-render β even if only Main needs the count. Thatβs unnecessary.
π§ Smarter State Management Tips
π§Ό Lift State Only When Needed
Donβt store state at a parent level if it only affects one child. Keep state local when possible.
function Main() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>{count}</button>; } π₯ Keep state close to where itβs used.
β π¦ Use useMemo and useCallback Wisely
Prevent unnecessary recalculations or prop updates.
const memoizedValue = useMemo(() => expensiveCalc(data), [data]); const handleClick = useCallback(() => { console.log("Clicked!"); }, []); β
π§© Memoize Components with React.memo
const Header = React.memo(function Header() { console.log("Header rendered"); return <h1>Header</h1>; }); Now Header only re-renders if its props change β not every time its parent re-renders.
β π§΅ Split Components Intentionally
Break components into smaller pieces to isolate re-renders. Instead of one giant Dashboard component, split it into Chart, Stats, and UserList.
β π Use State Libraries When Needed
For global state, use tools like:
Zustand β lightweight and intuitive
Redux Toolkit β modern Redux without boilerplate
Jotai/Recoil β minimal and scoped
These help prevent "prop drilling" and isolate reactivity.
π¬ Whatβs Your Favorite State Management Trick?
Top comments (0)