Weird behaviour of React component that writes to cookies

Viewed 72

I have a simple component, that writes to cookies. Minimal working example:

function App() {

  // stores cookie
  function setCookie(name: string, value: string, days: number) {
     ...
  }
  // reads cookie
  function getCookie(name: string) {
    ...
  }

  const cookieName = 'testCookie';

  const cookieValue = getCookie(cookieName);
  console.log('cookie value ', cookieValue);

  if (!cookieValue) {
    console.log('going to set cookie');
    setCookie(cookieName, 'test', 1);
    return <h2>Cookie was stored</h2>;
  }

  return <h2>Cookie already exists</h2>
}

export default App;

So I want to set cookie on the first run and let the user know that it was stored with Cookie was stored output. On the second run the Cookie already exists would be displayed.

However I immediately see Cookie already exists EVEN when the code executes and logs going to set cookie. The Cookie was stored is never displayed.

I thought there is a re-render happening, but it is not definitely full re-render as the cookie value is logged only once.

Please if you do know why is this behaving in this manner, let me know. Thank you very much!

1 Answers

You can solve this issue by storing this in a state variable:

import {useState, useEffect} from 'react'
function App() {

    // stores cookie
  function setCookie(name: string, value: string, days: number) {
     ...
  }
  // reads cookie
  function getCookie(name: string) {
    ...
  }

  const [cookieState, setCookieState] = useState(null)

  useEffect(() => {
    const cookieName = 'testCookie';

    const cookieValue = getCookie(cookieName);
    console.log('cookie value ', cookieValue);

    if (!cookieValue) {
      console.log('going to set cookie');
      setCookieState(cookieName, 'test', 1);
    }
   }, [])

  return cookie ? <h2>Cookie already exists</h2> : <h2> Cookie doesn't exist </h2>
}

export default App;
Related