I am trying to use useEffect
inside a functional component which should only run when the component mounts, but it says that:
Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."
React Code
React Error:
Change render
in your <Route ... />
into component
.
https://stackoverflow.com/a/53936972/12101554
render
doesn't seem to work with React Hooks, but component
does.
Per @rishat on StackOverflow,
[Using the render prop] saves you runtime because no lifecycle methods are run, ...
Source: https://stackoverflow.com/a/48152635/12101554
The useEffect()
React Hook is similar to the React.Component
lifecycle methods (componentDidMount
, componentDidUpdate
, and componentWillUnmount
all in one {plus a few more}), so when you use render
the Hooks don't work
The source code of react-router-dom
also shows us this:
if (component)
return match ? React.createElement(component, props) : null
if (render)
return match ? render(props) : null
As you can see, when you use render
, you aren't actually calling React.createElement
so Hooks and lifecycle methods don't work. However, when you use component
, they do work.