Optimizing React Performance by Relocating State
When working with React, managing state efficiently is crucial for optimizing performance. A common mistake developers make is placing state too high in the component hierarchy, causing unnecessary re-renders of unrelated components. In this article, we’ll explore this issue and how to fix it using state relocation.
The Problem: Unnecessary Re-renders
Consider the following example:
export default function App() {
const [firstName, setFirstName] = useState("");
return (
<>
<form>
<input
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</form>
<PageContent />
</>
);
}
At first glance, this setup might seem fine, but there's a hidden performance issue. Whenever the input field updates (firstName state changes), the entire App component re-renders. This means that both <form> and <PageContent /> re-render even though PageContent doesn't depend on firstName.
Since <PageContent /> is a potentially heavy component (holding the entire page’s content), this frequent re-rendering can be expensive and negatively impact performance.
The Solution: Relocate the State
The best way to solve this problem is by moving the firstName state closer to where it's actually needed—in this case, inside the <Form /> component.
Here’s the optimized version:
export default function App() {
return (
<>
<Form />
<PageContent />
</>
);
}
function Form() {
const [firstName, setFirstName] = useState("");
return (
<form>
<input
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</form>
);
}
Why is this better?
When to Relocate State
While lifting state up is useful for sharing data between components, it's important to only keep state at the highest level necessary. A good rule of thumb:
✅ Keep state as local as possible to avoid excessive re-renders. 🚫 Avoid placing state at the top-level unless it needs to be shared across multiple components.
Conclusion
State management in React is all about balancing reactivity and performance. By ensuring that state is only kept where it’s needed, we can reduce unnecessary re-renders, improve efficiency, and build more performant React applications. Always consider where your state lives and optimize accordingly!
Frontend Developer, 7+ years | React, Redux, Next.js
1ymoving state placing to a usage is a great idea! and for forms to minimize rerenders it’s good to use uncontrolled components with react-hook-form lib