Getting current value of variable outside the useEffect in React

Viewed 162

I am getting a response from django server and I need after that to set clock variable to true, because than I use that variable in a component.

let clock = false;
useEffect(() => {
      switch (true) {
        
      ........

        case dataParsed.type === "ClockInfo":
          {
            clock = true;
          }
          break;
      }
    };
  }, []);
<Header word={catchword} socketRef={socketRef} clock={clock} />

The clock value doesn't change correctly, it always shows false. I know that is cause it brings back to the false value every time react renders components, so how can I do it correctly?

I tried to use useRef, but it doesn't help at all. In my component I have a condition which start to work when clock == true.

3 Answers

Since you're trying to use the value in your render output, you must use state. Setting state is the only way to tell react to rerender the component.

const [clock, setClock] = useState(false);
// ...
  case dataParsed.type === "ClockInfo": {
    setClock(true);
    break;
  }

A ref can let you have a persistant value from one render to the next, but it can't initiate rendering so it's not the right tool for your case.

Try, if this works

import { useState } from 'react';
const [clock,setclock] = useState(false);
useEffect(() => {
      switch (true) {
        
      ........

        case dataParsed.type === "ClockInfo":
          {
            setclock(true);
          }
          break;
      }
    };
  }, []);

add dataParsed in useEffect dependency array.. it will called when even dataParse's value changed

import { useState } from 'react';
const [clock,setClock] = useState(false);
useEffect(() => {
      switch (true) {
      ........

        case dataParsed.type === "ClockInfo":
          {
            setClock(true);
          }
          break;
      }
    };
  }, [dataParsed]);


<Header word={catchword} socketRef={socketRef} clock={clock} />
Related