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

84
Views
React.useCallback not updating its implementation when state is updated

I am creating a todo application using React hooks. The way I am doing this is by creating a context for a single todo and a context for all todos. The NewTodoContext would be parent to the new todo react components and will take up responsibilities like having an internal state, providing callback to update that state, reset that state and update AllTodosContext once user confirms todo formation.

The NewTodoProvider would look like

function NewTodoProvider({ children }){
   const [todo, setTodo] = React.useState(DEFAULT_EMPTY_TODO_STATE);
   
   const [ addTodo ] = React.useContext(AllTodosContext);
   
   const updateTodo = React.useCallback((todoFragment) => {
     // setTodo({...todo, ...todoFragment}) 
   }, [todo]);
   
   const confirmTodo = React.useCallback(() => { addTodo(todo) }, [todo]);

   return (
     <NewTodoContext.Provider value={{ todo, updateTodo, confirmTodo }}>
         { children }
     </NewTodoContext.Provider>
   )
}

The AllTodosProvider would look like

function AllTodosProvider({ children }){
    const [todos, setTodos] = React.useState();
    const addTodo = React.useCallback((todo) => {
        setTodos([...todos, todo]);
    },[todos]);

   return (
     <AllTodosContext.Provider value={{ todos, addTodo }}>
         { children }
     </AllTodosContext.Provider>
   )

}

and the React tree would be like

<AllTodosProvider>
   <DifferentComponents />
   <NewTodoButton />
   <DifferentComponents />
</AllTodosProvider>


// NewTodoButton would open up into

<NewTodoProvider>
   <SomeFormComponent />
</NewTodoProvider>

Now coming to the issue I am facing. As you can see, the confirmTodo is wrapped in useCallback with todo as a dependency so that it has the latest state of NewTodoProvider, but that doesn't seem to be the case. When confirmTodo is called, it seems to pick up the default state, hinting that its implementation remained unchanges inspite of state changes. What am I missing here?

about 4 years ago · Juan Pablo Isaza
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!