Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
is it alright to have a ref on state (from a reducer) to avoid creating new callbacks?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!