I often have a use case where there is some state in reducer and it needs to be accessed in some callback (useCallback) as well
const [state, dispatch] = useReducer(reducer, initialState);
...
const handleAction = useCallback(()=>{
// dependency on state
},[])
to avoid running useCallbacks on every state change, I reach out for a ref and have the state assigned to it on every render
stateRef.current = state;
and then where ever i have to use something from state in a callback, it is accessed from the stateRef. Is this a right way of doing it?
If you are simply updating the stateRef from the component body then this isn't the most correct way as this would be considered an unintentional side-effect. If not using an useCallback hook with a dependency on the state to re-enclose the current state value in a callback function then an useEffect with a dependency on the state value is suggested.
const [state, dispatch] = useReducer(reducer, initialState);
const stateRef = useRef();
useEffect(() => {
stateRef.current = state;
}, [state]);
const handleAction = ()=>{
// access stateRef.current
};
This is effectively what useCallback accomplishes though, but in a more succinct way.
const [state, dispatch] = useReducer(reducer, initialState);
const handleAction useCallback(() => {
// access current state value closed over in scope
}, [state]);