Solution to the asynchronous problem of using useState data in React

Problem: Use useState for data storage in React's function components, resulting in asynchronous data and unable to obtain the latest current data in time.
Reason: This is because events in React are divided into synthetic events and native events. Both synthetic events and hook functions are asynchronous, and native events are synchronous. Because useState is an asynchronous event, there may be situations where the latest value cannot be obtained in time.
Solution: Use useRef to store data first, then use useEffect to monitor data changes and update them.

const [info, setInfo] = useState();

const infoRef = useRef();

useEffect(() => {
    
    
    infoRef.current = info;
  }, [info]);

Where info data needs to be used later, you only need to get infoRef.current to get the latest info data content.

Guess you like

Origin blog.csdn.net/qq_45488467/article/details/126229537