Avoiding unnecessary renders helps your app run faster and smoother by not updating parts of the screen when nothing has changed.
Avoiding unnecessary renders in React
const MemoizedComponent = React.memo(Component); const memoizedCallback = React.useCallback(() => { // function code }, [dependencies]); const memoizedValue = React.useMemo(() => computeValue(), [dependencies]);
React.memo wraps a component to skip re-render if props are the same.
useCallback keeps a function the same between renders unless dependencies change.
onClick or label props change.const Button = React.memo(({ onClick, label }) => { console.log('Button rendered'); return <button onClick={onClick}>{label}</button>; });
handleClick is memoized so Button won't re-render just because Parent re-renders.const Parent = () => { const [count, setCount] = React.useState(0); const handleClick = React.useCallback(() => { setCount(c => c + 1); }, []); return <Button onClick={handleClick} label="Click me" />; };
useMemo caches the result of a heavy calculation until input changes.const expensiveValue = React.useMemo(() => { return computeHeavyTask(); }, [input]);
In this example, the Child component only re-renders when the count changes. Typing in the input does not cause Child to re-render because it is wrapped with React.memo. You can see "Child rendered" in the console only when the count changes.
import React from 'react'; const Child = React.memo(({ value }) => { console.log('Child rendered'); return <div>Value: {value}</div>; }); export default function App() { const [count, setCount] = React.useState(0); const [text, setText] = React.useState(''); return ( <div> <button onClick={() => setCount(count + 1)}>Increment Count</button> <input aria-label="Input text" value={text} onChange={e => setText(e.target.value)} placeholder="Type here" /> <Child value={count} /> </div> ); }
Wrapping components with React.memo only works if props are simple and stable.
Use useCallback and useMemo to keep functions and values stable between renders.
Too much memoization can make code complex, so use it only when you notice performance issues.
Avoid unnecessary renders to make your app faster and smoother.
Use React.memo to skip re-rendering components when props don't change.
Use useCallback and useMemo to keep functions and values from changing needlessly.