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

280
Views
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 answers
Answer question

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 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!