Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

86
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda