Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda