Search code examples
reactjsreact-router-domuse-effectuse-statecurtains.js

ReactJS fire up useEffect with window.location.reload() inside just one time on every page visit


please forgive me for this kind of amateur question.
I have the following problem which I can´t solve by my own:
I´m working on a cra-project in which I´m using a continually distorted image animation and scroll animation from curtainjs, and react-router-dom for my routing.
When I switch to About page and go back from there, the images are not visible anymore, just after reloading, so my thought was to relaod the page every time I get back onto. I used the useEffect-Hook with window.location.reload() inside a simple logic. If I understand it wright, useEffect runs on every render change.
So I thought maybe there is a problem with the continually animation of the images because useEffect repeats in a continuous loop - even when the array at the end of the hook is there and empty.

So at least my question is how to fire up window.location.reload() just one time after I click go back in About.js, even if there are any kind of rerenderings because of the image animations on the main page (App.js). Is it possible?

Hope somebody can help me out, thank you!

App.js:

function App() {
  const [loading, setLoading] = useState(1);

  useEffect(() => {
    if (loading === 1) {
      window.location.reload();
      console.log('page is loading')
      setLoading(loading + 1);
    } else {
      console.log('page already loaded');
    }
  }, []);
  return (
    <>
        ...
    </>
  );
}

export default App;

Solution

  • Try something like this.

    function App() {
      const [loading, setLoading] = useState(false);
    
      useEffect(() => {
        if (loading) {
          window.location.reload();
        } else {
          console.log('page already loaded');
        }
      }, [loading]);
      return (
        <>
            ...
             <button type="button" onClick={() => setLoading(true)}>Refresh page</button>
            ...
        </>
      );
    }
    
    export default App;
    

    The button is just an example, but you can change the loading state using something else.

    If you don't want to use the window.location.reload() you can try this:

    function App() {
              const [loading, setLoading] = useState(false);
            
              useEffect(() => {
                if(loading) {
                 setLoading(false)
    }
            }, [loading]);
              return (
                <>
                    {loading ? null : (
                     <>
    ...<button type="button" onClick={() => setLoading(true)}>Refresh page</button>...
                     <>
                   )}
                </>
              );
            }
            
            export default App;