Search code examples
javascriptreactjsrefresh

How to setState after the page reloads


On mobile screen, the drop down navigation menu stays open even after a user has been directed to a page. I want it to close after any page reloads.

This is what i've tried in my navigation.jsx:

useEffect(() => {
    console.log("Open? ", open);
  }, [open]);

  useEffect(() => {
    if (window.performance.getEntriesByType) {
      if (
        window.performance.getEntriesByType("navigation")[0].type === "reload"
      ) {
        console.log("reloaded");
        setOpen(false);
      }
    }
  }, []);

I expected this to render every time the navigation pane re-renders but since its outsider of the browser router Navigation.jsx only renders once in the app unless there is a change in authentication etc because menu items change.

App.js

function App() {
  return (
    <>
      <BrowserRouter>
        <Navigation />
        <Routes>
//Bunch of code
        </Routes>
        <Footer />
      </BrowserRouter>
    </>
  );

I'm trying to figure out which dependencies to add or just how to go about ensuring that when there is a page reload(doesn't matter which page) then setOpen(false).


Solution

  • In a single page application (In this case React), the browser doesn't fully reload the page but rather it is the JavaScript that does the magic on replacing the items in the page

    There's 2 solutions for your issue:

    1. Call setOpen(false) in onClick of any of your navigation items
    2. Listen to history change (Not recommended) and set it to close whenever that happens:
    import { useLocation } from 'react-router-dom';
    let location = useLocation();
    
    useEffect(() => {
      console.log('Open? ', open);
    }, [open]);
    
    useEffect(() => {
      // Set to close whenever location changed
      setOpen(false);
    }, [location]);
    

    Documentation on second solution: https://reactrouter.com/en/main/hooks/use-location