This has nothing to do with hooks or not, it's based on how React Router Dom works.
If don't you need the match
, location
, or history
props, then you can simplify your component;
<Route path='/someroute'>
<SomeComponent someprop={someprop}/>
</Route>
If you do need those, then you can use one of React Router's hooks in your child component to get them, you can use the render prop of the route. You definitely don't want to try this with the component prop as that will create a new component in every render.
<Route path='/someroute' render={routeProps=><SomeComponent {...routeProps} someprop={someprop}/>} />
Another route to do this is using the withRouter Higher order component:
//outside of the parent component
const SomeComponentWithRouter = withRouter(SomeComponent);
//In the render function:
<Route path='/someroute'>
<SomeComponentWithRouter someprop={someprop}/>
</Route>
Edit for posters questions:
- The render tag you showed, does it cause unnecessary re-renders? I
read something about that.
The render prop doesn't cause unnecessary re-renders as far as I'm aware. What you might be thinking of is that trying the same as the render prop with the component prop causes issues:
From React Router's documentation:
When you use component (instead of render or children, below) the
router uses React.createElement to create a new React element from the
given component. That means if you provide an inline function to the
component prop, you would create a new component every render. This
results in the existing component unmounting and the new component
mounting instead of just updating the existing component. When using
an inline function for inline rendering, use the render or the
children prop (below).
https://tylermcginnis.com/react-router-pass-props-to-components/
Reactjs - `component` vs `render` in Route
- And I must ask, could you post some beginner-friendly reference
about the 'withRouter' you were talking about?
Again, I must refer you to React Router's documentation. It is one of the best sources of information about React Router and is kept up to date.
The main gist of withRouter is that it's a higher order component and will basically give you a new version of your component that always has the match
, history
, and location
props passed in (match is based on the first matched Route up the component hierarchy).
There's not really much else to say about withRouter, I have an example of how to use it, and it adds those 3 props to your component.
I'd personally recommend using the hooks that React Router provide if you are working with function components as they don't require higher order components. Like any other hooks, they can be more easily composed with any custom hook or function component.
https://css-tricks.com/the-hooks-of-react-router/