โ 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)