background
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.
code
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 [
data,
(val: any, callback: any) => {
cbRef.current = callback;
setData(val);
},
];
};
export default useSyncState;
use
const [data,setData] = useSyncState(0);
setData(1, function (data) {
console. Log ("I am the latest value:", data);
})