[Java] [React.useRef] What to do when the latest state cannot be referenced in the event listener

1 minute read

Introduction

This is a workaround when State (state) cannot be handled correctly in the event listener of the function component.

When you try to refer to the state of React.useState() in the callback function of the event listener, the value may not be up to date.

Something that doesn’t work

  1. Declare a State called counter
  2. Click the button and add +1 to the counter
  3. Event listener that responds to click fires func()
  4. Output the value of counter

Function Component


// ①
const [counter, setCounter] = React.useState(0);

// ④
const func = () => {
  console.log(counter);
};

// ③
React.useEffect(() => {
  window.addEventListener("click", func);
}, []);

// ②
return (
  <button onClick={() => setCounter(counter + 1)}>
    button
  </button>

**In this example, the value output from ④ console.log(counter) is always 0. ** It is fixed to the value of counter at the time of registration of the event listener, and the output does not change even if the state is updated.

I don’t know how many times I clicked this…

use useRef()

You can always refer to the latest status by using React.useRef().

a working example



const [counter, setCounter] = React.useState(0);

// add to
const counterRef = useRef(); // create ref object
counterRef.current = counter; // ref refers to counter


const func = () => {
  // output ref
  console.log(counterRef.current);
};

// -----The following is unchanged-----
React.useEffect(() => {
  window.addEventListener("click", func);
}, []);

return (
  <button onClick={() => setCounter(counter + 1)}>
    button
  </button>

Instead of using counter in your callback, use counterRef.current. By doing this, you can refer to the latest state.

Summary

If you cannot refer to the latest state in the event listener of the function component, use Ref that refers to State instead of using State in the callback.

By doing this, you can refer to the latest state.