It is very common when you build an application with routing to have some kind of common design with state between routes. For example a sidebar or some information content, like signed in user, or current time. Usually this is handled by layouts that are wrapped around our route content. It is very important for a layout to maintain its state and not re-render on route change.
In this simple and short guide I will show you how you can manage your routing in React with React Router and layouts that hold their state and don’t re-render on route navigation.
Let’s first define the components we will use for each page. We will keep them as simple as just one line of code per component. Just for the example.
Now let’s define also our layouts. We will have two layouts. Page one and two will use layout one and page three and four will use layout two.
Our layouts will display just a simple heading for example purposes as well as the special
children property which will take the contents between the opening tag of the layout and it’s closing tag and provide it in the layout function as this exact property —
You can read more about the
children special property in the official documentation of React about Composition vs Inheritance here.
Now the only thing left to define is the routes themselves.
The most important part here is our
RouteWrapper component that is just an abstraction for our
Route. We are passing
layout to it and then we are just wrapping the component in our layout. It is important here to use the
render prop of the
Route in order to have a layout that maintain it’s state and don’t re-render upon route navigation.
We have created a layout for our different pages that doesn’t change it’s state and doesn’t re-render upon route navigation. You can go ahead and test the results by adding some state or just by simply playing with the
componentDidMount lifecycle function of the
Layout components to see they just mount once when you access a page with them and then they do not re-render when you navigate to a different page with the same layout.
Feel free to comment and share your ideas and suggestions! Thanks for reading 🙏