(react router)component vs render in Route with demo code

Frankie
1 min readApr 21, 2020

--

Many people may know that there are two ways we usually use to pass component to Route : render and component to render when the app’s location matches that path.

For example:

<Route exact path="/" component={User} />
or
<Route exact path="/" render={()=><User/>} />

Or we can pass some props like this:

<Route exact path="/" component={()=><User something="something"/>} />
or
<Route exact path="/" render={()=><User something="something"/>}/>

It’s not the best solution for using component. The reason is that behind the scenes it is using React.createElement to create a new React element that means if you provide an inline function it will create a new component every render.

This is a short demo code, when we using render and change counter value, it will not unmount the component and showing the correct counter value. However, when we click on the component it can show the correct counter value but each time we change the counter value, it will unmount one time.

--

--

Frankie
Frankie

Written by Frankie

Hi, I am interested in IT field including front-end, back-end, database, networking.

No responses yet