Get the latest state value of usestate in user-defined hooks synchronization



When we don’t use hook, we can get the latest value in the setstate callback function

When using react hook, the latest value can only be obtained in useeffect

But sometimes in our business scenarios, we need to get the latest change value of the variable synchronously for the next operation;

At this time, we can encapsulate a hook and get the latest status value through the callback function in combination with useref.


import { useEffect, useRef, useState } from 'react';

 *Custom usestate
 * @param state
 * @returns
const useSyncState: any = (state: any) => {
  const cbRef: { current: any } = useRef();
  const [data, setData] = useState(state);

  useEffect(() => {
    cbRef.current && cbRef.current(data);
  }, [data]);

  return [
    (val: any, callback: any) => {
      cbRef.current = callback;

export default useSyncState;


const [data,setData] = useSyncState(0);

setData(1, function (data) {
    console. Log ("I am the latest value:", data);