4
useEffect(() => {
  console.log("Effect runs");

  return () => {
    console.log("Cleanup runs");
  };
}, []);

If window.location.reload() is called anywhere in your application, will the cleanup callback of the useEffect fire?

1
  • 1
    You could easily define component with such effect and also with button, when you click it invoke reload function and observe results Commented Aug 17 at 6:27

2 Answers 2

10

Typically no, the cleanup function in useEffect won’t run on window.location.reload(). Cleanup only runs when React unmounts a component or reruns the effect, but a full page reload wipes out the JS runtime before React can do anything. If you need logic before reload/close, use beforeunload instead.

Sign up to request clarification or add additional context in comments.

2 Comments

"If you need logic before reload/close..." perhaps you don't. beforeonload would be the way to do that, but there are very few cases where this is actually necessary.
100% agree, beforeunload is rarely needed, I just mentioned it as the way to handle reload/close since reacts cleanup won’t fire in that case.
3

When we call window.location.reload():

  • The entire page i.e. React, the DOM, and our JavaScript environment are torn down by the browser.

  • This does not give React a chance to unmount component, instead the browser just throws everything away and reloads from scratch, which means React does not run our cleanup functions.

    Let's take this example :

useEffect(() => {
  console.log("Effect runs in line 1");

  return () => {
    console.log("Cleanup runs in line 15");
  };
}, []);

const handleReload = () => {
  window.location.reload();
};

When the component first mounts, we'll see 'Effect runs in line 1', now when we click a button that triggers reload, the browser discards the page. So we'll never see 'Cleanup run in line 15', cause React never got a chance to execute it.

Coming to the point answer : No window.location.reload() does not trigger the useEffect cleanup.
The browser reload wipes the page, React is gone, so React can’t run the cleanup.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.