useStateRef
function useStateRef(initialState) {
const [state, setState] = useState(initialState);
const ref = useRef(state);
const dispatch = useCallback((val) => {
ref.current = typeof val === 'function' ?
val(ref.current) :
val;
setState(ref.current);
}, []);
return [state, dispatch, ref];
}
Example:
const [myState, setMyState, myStateRef] = useStateRef(defaultState);
useEffect(() => {
if(SOMES_CONDITION_STUFF) {
setTimeoutOrIntervalSomething(() => {
console.log(myState.current, 'is always correct');
});
}
});