0

I'm trying to use the react useEffect hooks to check if the cookies is accepted on the first render. But when I test it by logging out and logging in again or closing and reopening the browser, it doesn't behave the way it should. By behavior I mean each time the user logs in, it should render the cookie banner. What am I missing?

This is the relevant code.

 const firstRender = useRef(true);

  React.useEffect(() => {
  firstRender.current === false;

    return () => {
      if (firstRender.current === true) {
        cookiesAccepted === 'true';
      }
    };
  }, [handleAcceptCookies]);
Waiz
  • 503
  • 2
  • 6
  • 15
  • There's quite a bit of context missing here. Do you ever set `firstRender` to false? Does `handleAcceptCookies` definitely change and trigger the effect? What exactly does "it doesn't behave the way it should" mean? – DBS Mar 17 '21 at 10:14
  • I can't see if it is being triggered. I can only see if I clear the browser cache, then it runs the cookie banner. By the 'behavior' I mean, each time the user logs in, it should run the cookies banner. – Waiz Mar 17 '21 at 10:18
  • What you current code will do is: Whenever `handleAcceptCookies` changes (or is set on first load) it will then set `firstRender` to false. When the component is unmounted, it will check if first render is `true` (Which it never will be unless there's more code than we can see here) and if so, compare `cookiesAccepted` to 'true' (The triple === is a comparison not an assignment) – DBS Mar 17 '21 at 10:29
  • I'm not sure what is happening here. `===` is checking if the value is equal, not setting that to the value you desire. So inside your `if` it seems alright, but then if you want to change the value, you should do `firstRender.current = false` and `cookiesAccepted = true`. Also, if you want to trigger an rerender with a modal or something, you would have to use `useState` - `useRef` does not trigger a rerender. – Konstantin Mar 17 '21 at 10:29
  • Thanks! I've used this reference: https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render , here they mention using the useRef for the first render. – Waiz Mar 17 '21 at 10:41

0 Answers0