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

282
Vistas
How to use setState function synchronously in zustand?

There are parts of my app that must work synchronously. I am using zustand. The problem is that zustand's setState function works asynchronously. Please let me know if there are any other libraries that support synchronous state changes or any tricks.

App.js (react example)

// in real
import create from 'zustand'
import logo from './logo.svg';
import React, { useEffect } from 'react';

const useStore = create(() => ({
  counter: 0
}))

function App() {
  const { counter } = useStore()
  useEffect(() => {
    console.log(counter) // output: 0
    useStore.setState({ counter: counter + 1 })
    console.log(counter) // output: 0
    useStore.setState({ counter: counter + 1 })
    console.log(counter) // output: 0
  }, []);

  return (
   <div></div>
  );
}

export default App;

// my hope

// ...
useEffect(() => {
    console.log(counter) // output: 0
    useStore.setState({ counter: counter + 1 })
    console.log(counter) // output: 1
    useStore.setState({ counter: counter + 1 })
    console.log(counter) // output: 2
  }, []);


// ...
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is in your counter definition.

const { counter } = useStore()

should be

 const counter = useStore((state)=> state.counter)

Here's an example of how your code should look:

store:

const useStore = create(() => ({
  counter: 0,
  addOne: () =>
        set((state) => ({
            counter: state.counter +1
        })),
 }))

App:

function App() {
  const counter = useStore((state)=> state.counter)
  const addOne = useStore((state)=> state.addOne)

  useEffect(() => {
   let interval = setInterval(() => addOne(), 1000)
   return () => clearInterval(interval)
  }, [counter]);

  return (
   <div>{counter}</div>
  );
}

I'm throwing the setInterval function in there so that it updates once every second. Using the counter state as a dependency for useEffect will cause the component to re-render every time the state is changed.

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