1

I have this Skip component to conditionally skip pages. I noticed that instead of skipping ONE page, it skips two pages! I suspected that it might be the Strict Mode running the UseEffect code twice. I turned the Strict Mode off and now the Skip behaves as it should, i.e. skipping just ONE page. Is this a bad practice to turn strict mode off? I was assuming it was meant to help development, but it really threw me off for a couple of hours trying to figure out what was wrong!

const Skip = () => {
  // nav is a Zustand store reference that holds the page state
  // Zustand state updates need to be run in useEffect otherwise console throws errors.
  useEffect(() => {
    if (nav.isNextClicked) {
      nav.nextPage();
    }
    if (nav.isBackClicked) {
      nav.prevPage();
    }
  }, []);

  return <div></div>;
};

export default Skip;
5
  • That error is absolutely because of strict mode. Debatable whether turning it off is acceptable practice... but this does smell like one of the cases it's supposed to prevent. useEffect is not supposed to have side effects, is there any way you could move that logic higher in the component tree? Commented Nov 26, 2023 at 18:39
  • @SoZettaSho Thanks for the reply. I assumed that useEffect hook is specifically designed for handling side effects. Isn't it the primary purpose of useEffect to perform tasks that have side effects, such as this code? I woud love to know what I am doing wrong here though. Commented Nov 26, 2023 at 18:45
  • 2
    Apologies, "not supposed to have side effects" wasn't the right wording so much as that effects should generally be pure/idempotent. I can't seem to find the issue where the react devs explicitly state the motivation for strict mode running everything twice, but see react.dev/learn/… Commented Nov 26, 2023 at 18:53
  • Can't say more without knowing the meaning of nav.isNextClicked, etc... but perhaps there's a way to keep which page should be shown in pure js, and/or calculate the next page to be shown based on the current page and nav state...? Commented Nov 26, 2023 at 18:55
  • looks like you are handling a user action in an effect? if so, move the logic to the event handler. more Commented Nov 27, 2023 at 11:57

0

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.