-3

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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. 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

enter image description here

React Error:

React Error

Riddell
  • 1,429
  • 11
  • 22
  • 2
    **DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text. For more information please see the Meta FAQ entry [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/a/285557). – nobleknight Jun 11 '21 at 13:04

1 Answers1

-1

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.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34