简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM