pa1nd
pa1nd

Reputation: 432

setState in useEffect with state as condition

I want to hide a mobile menu once the pathname changes (using ReactRouter).

The code below shows me a warning because I dont track mobileOpen as a dependency. But it works.

const Navbar: React.FC<Props> = props => {
  const { pathname } = useLocation()
  const [mobileOpen, setMobileOpen] = useState(false)

  useEffect(() => {
    if (mobileOpen) setMobileOpen(false)
    main.current?.scrollTo(0, 0)
  }, [pathname, main])

...

As soon as I add it to the dependency array, the code navigation does not open anymore as it would directly trigger the effect and close again.

Is that the correct way of doing it? Would there be a better way of preventing unnecessary renders?

Upvotes: 1

Views: 501

Answers (1)

Eusbolh
Eusbolh

Reputation: 126

As far as I understand from your code, you actually don't need to check if mobileOpen is true or not. I guess what you want is setting mobileOpen to false no matter what when that effect is triggered. I believe you'll be fine if you update your code like this:

useEffect(() => {
  setMobileOpen(false);
  main.current?.scrollTo(0, 0);
}, [pathname, main])

If you still need to check mobileOpen has a truthy value for a reason, you can use setMobileOpen((prevState) => { ... }); syntax too.

Upvotes: 2

Related Questions