🧠 React State Optimization: Avoiding Unnecessary Renders
React is designed to efficiently update the DOM when your application state changes. But what if you’re changing the state to exactly the same value it already holds? Did you know that you can prevent unnecessary re-renders and improve performance just by being smart about how you update state?
In this post, we’ll explore:
URLSearchParams
Let’s start with a simple example using useState
.
const [count, setCount] = useState(0);// Somewhere later in the codesetCount(0); // No rerender if `count` is already 0
React is smart! If you set the state to the same primitive value, it won’t rerender the component. It compares the current value with the new one using Object.is()
and skips rerendering if they are equal.
Now consider this case:
const [state, setState] = useState({ count: 0 });setState({ count: 0 });
Even though the values inside are the same, this creates a new object, and React sees it as a change — so it rerenders. Why?
Because:
{ count: 0 } !== { count: 0 } // different references!
You can avoid this by returning the previous state directly if nothing changed:
setState((prev) => prev); // No rerender
Or by performing a deep comparison yourself if needed.
Before calling a state update function, you can first check whether any value actually changed. If not, just return the previous state. This applies to both useState
and useReducer
.
This approach gives you precise control and avoids unnecessary work for React — which can be a huge win for performance in large apps!
URLSearchParams
StateLet’s put this into practice with a real-world scenario:
Imagine a search page where you store the entire URLSearchParams
object in state — not just the search query
, but the full set of parameters.
const [searchParams, setSearchParams] = useState(new URLSearchParams(window.location.search));
You have a form where users can submit a search term, and each submission calls:
setSearchParams((prevParams) => {const newParams = new URLSearchParams(formInput);// If the new parameters are identical, skip updateif (newParams.toString() === prevParams.toString()) {return prevParams; // No rerender}return newParams;});
With this check in place:
💡 Try it out in your browser console:
console.log('App rerendered')
in your App
component.console.log('Search params updated')
in your setSearchParams
callback.React gives you the tools to write performant applications, but it’s up to you to use them wisely. By:
You can significantly reduce unnecessary renders and keep your UI lightning fast.
Want to go deeper? Try applying these optimizations in your own app and see the difference.
Happy coding! ⚛️✨
Quick Links
Legal Stuff
Social Media