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

Introduction

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

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

Examples that don't work

  1. Declare a State called counter
  2. Click the button to add + 1 to counter
  3. The event listener responding to the 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 by ④ console.log (counter) is always 0. ** ** It is fixed at 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 on it ...

Use ʻuseRef () `

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

Examples that work



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 the callback, use counterRef.current. By doing this, you can refer to the latest state.

Summary

If the latest state is not visible in the function component's event listener, use Ref to reference State instead of using State in the callback.

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

Recommended Posts

[React.useRef] What to do when the latest state cannot be referenced in the event listener
What to do if the adb command cannot be executed
What to do when the error "Non-static variable x cannot be referenced from static context" in Java. Lessons from the very first step in programming Remarks 01
What to do when Git Repository cannot be displayed in Team Explorer for Eclipse in Azure
What to do when the changes in the Servlet are not reflected
[Rails] What to do when rails db: migrate cannot be done because there is no table referenced by the foreign key
What to do when CentOS cannot be started with VirtualBox on Catalina
What to do when IllegalStateException occurs in PlayFramework
What to do when the value becomes null in the second getSubmittedValue () in JSF Validator
What to do when rails db: seed does not reflect in the database
[Ubuntu] What to do when MongoDB cannot be started due to a SocketException error
What to do when The SSL certificate has expired
What to do when "Fail to load the JNI shared library" is displayed in Eclipse
What to do when Method not found in f: ajax
What to do when Cannot apply expression operators to method binding
What to do when Cannot format given Object as a Date in convertDateTime of JSF
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
What to do when Rails on Docker does not reflect controller changes in the browser
What to do when "relation" hibernate_sequence "does not exist" in the ID column of PostgreSQL + JPA
What to do when an UnsupportedCharsetException occurs in a lightweight JRE
[Rails] What to do when the error No database selected and Unknown database appears in db: migrate
[Programming beginner] What to do when rails s becomes an error in the local development environment
[Ruby] What to do when the error "cannot load such file" appears when executing VS Code debug
What to do if the Rails page doesn't appear in Rails tutorial 1.3.2
What to do when you want to know the source position where the method is defined in binding.pry
What to do if Cloud9 is full in the Rails tutorial
What to do about the "cannot be read or is not a valid ZIP file" error
What to do if the app is not created with the latest Rails version installed when rails new
What to do when javax.batch.operations.JobStartException occurs
What to do if you forget the root password in CentOS7
What to do if you cannot roll back the migration (UnknownMigrationVersionError)
The first thing to do when you want to be happy with Heroku on GitHub with Eclipse in Java
What to do if Operation not permitted is displayed when you execute a command in the terminal
What to do if JavaMail cannot be used with OpenJDK 11 or later
[IOS] What to do when the image is filled with one color
What to do if the prefix c is not bound in JSP
What to do when Blocked Host: "host name" appears in Ruby on Rails
What to do and how to install when an error occurs in DXRuby 1.4.7
What to do if tomcat process remains when tomcat is stopped in eclipse
Notes on what to do when a WebView ClassNotFoundException occurs in JavaFX 12
What to do when a javax.el.PropertyNotWritableException occurs
What to do when undefined method ʻuser_signed_in?'
How to translate the error message into Japanese (What to do if you cannot log in for some reason)
What to do when you think you can't do Groovy-> Java in IntelliJ IDEA CE
What to do if the changes are not reflected in the jar manifest file
[Grails] Error occurred running What to do when the Grails CLI does not start
Androd: What to do about "The Realm is already in a write transaction in"
What to do if SPA URL loading cannot be detected by WebView shouldOverrideUrlLoading
What to do if ffi installation fails when launching an application in Rails
What to do if the server tomcat dies
What to do when ‘Could not find’ in any of the sources appears in the development environment with Docker × Rails × RSpec
When the server fails to start in Eclipse
[Rails] What to do when you want to generate an error that cannot be destory when foreign key restrictions are applied
What to do when debugging "Source not found"
What do you use when converting to String?
What to do if you can't get the text of an element in Selenium
What to do when Address already in use is displayed after executing rails s
What to do if you cannot execute with the command "Java package name / class name"
What to do if the debug gem installation fails
[Android] Solution when the camera cannot be started on Android 9
What to do if the Rails server can't start