React - useEffect not using updated value in websocket onmessage

Viewed 24

I have a simple issue where a state value updates in my code but is not using the new value. Any ideas what I can do to adjust this?

const [max, setMax] = useState<number>(10);

    useEffect(() => {
         console.log('max', max);              //This outputs correct updated value.

         ws.onmessage = (message: string => {
              console.log('max', max);         //This is always 10.

              if (max > 100) {
                    doSomething(message);
              }
         }
    },[]);

    function onChange() {
          setMax(1000);
    }


<Select onChange={onChange}></Select>   //this is abbrev for simplicity
1 Answers

Your useEffect is running only once, on the initial render, using the values from initial render, so max variable is closure captured and not updated in any way. But the solution will be pretty simple, using useRef and one more useEffect to update the ref variable when max variable updates.

const maxRef = useRef(10); // same value
const [max, setMax] = useState(10);

// Only used to update ref variable
useEffect(() => {
  maxRef.current = max;
}, [max]);

useEffect(() => {
  console.log("max", maxRef.current);

  ws.onmessage = (message) => {
    console.log("max", maxRef.current);

    if (maxRef.current > 100) {
      doSomething(message);
    }
  };
}, []);
Related