SoFunction
Updated on 2025-04-07

The problem of listening function in React component cannot obtain the latest state

Scene

In the useEffect event, the state value obtained after updating setState or redux is the first value, not the latest one

For example:

export default function Travel(props) {
    const divRef = useRef(null)
    const [count, setCount] = useState(0)
    const handleClick = () => {
        ('click',count);
    }
 
    useEffect(() => {
        ('click', handleClick)
        return () => {
            ('click', handleClick)
        }
    },[])
    ('out',count);
 
 
    return (
        <div ref={divRef} >
            <button onClick={() => {
        setCount(count => count + 1)
 
            }}>Click</button>
        </div>
    )
}

Or

const [flag,setFlag] = useState(false);
  
  const onClick = ()=>{
    setFlag(!flag)
    (flag)
  }
  
  useEffect(() => {
    ('click',onClick)
  }, []);

reason

I found some information to learn

Because the listener is bound to a function generated when the first render is rendered, the state in the context of this function is also the first value, so even if it is rendered many times later, because the function is bound to a function that is rendered for the first render, the state value is also old.

Solution 1

useEffect(() => {
    ('click', handleClick)
    return () => {
        ('click', handleClick)
    }
},[count])

Listen to changes in value, bind and unbind events

Solution 2

const stateRef = useRef(0)
const [state,setState] = useState();
 
const Function = ()=>{
    let data = ((stateRef));
    /*Function*/
     = newData;
    setState()
}  

Create variables by usingRef to change the value of state

Other situations

const stateRef = useRef(null);
 
useEffect(() => {
    if (
      ! ||
      (reduxState &&
        (reduxState) !== () &&
        () !== (?.id))
    ) {
       = ((reduxState));
    }
  }, [reduxState]);

For example, redux caches a string of data, which is used to control object movement, and can listen to redux state and assign value to stateRef.

Pay attention to prevent repeated assignments, otherwise it will cause jitter.

Determine whether the data has not changed and determine whether the redux data has been switched.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.