Simple Ways to Improve Your React App's Performance
Hi everyone! Today I want to talk a little about performance, something that sooner or later comes up in our day-to-day work.
Let's get started 📝
In React, rendering is a core concept. In simple terms, it's when a component first appears on the screen. A re-render is the same process happening again after the component is already on screen.
Both stages are normal parts of React's development cycle. The problem is when re-renders happen so often that the app starts showing signs of poor performance and becomes slow.
Let's say a home page has a search bar and several other heavy components.
When you type into the search bar, the whole page that contains it can be updated with every character. That's because when a component's state changes, the component renders again.
The list is part of the search, but the other components aren't. If all those components re-render every time someone types in the search bar, we can imagine how that affects the user experience.
You might think about moving this state into a hook and calling it alongside the other components. But the heavy components may still re-render together because the state is still connected to them all. You could also pass the state as props, but that can still cause unwanted re-renders if the state is shared with those components.
“Okay, Isabel... I get it. How can we solve this if hooks and props aren't helping?”
— An annoyed developer
The solution is quite simple: think of a pyramid. We'll move everything that uses the state farther down the component tree. All we need to do is isolate the state, whether it's hidden inside a hook, used directly, or passed through props.
Move the search bar into a smaller component:
export default function SearchBar() { const [searchInput, setSearchInput] = useState(""); const onSearch = (e) => { e.preventDefault(); setSearchInput(e.target.value); }; return ( <> <input type="search" placeholder="Search here" onChange={onSearch} value={searchInput} /> <List search={searchInput} /> </> ); }
Then call it where the search bar originally was. The final result looks like this:
export default function App() { return ( <> <SearchBar /> <SlowComponentOne /> <SlowComponentTwo /> <VerySlowComponent /> </> ); }
The state still changes, but now it only affects the smaller search bar component. The parent component that renders the heavy components no longer has state, so it doesn't re-render.
This is a very simple example of how re-rendering works in React and how it can help us find quick solutions in our day-to-day work. There's much more to explore, though. If you'd like to see more examples of different approaches to re-rendering, let me know.
See you next time 😄
