Next.js Discord

Discord Forum

Update state in Zustand via Interval

Unanswered
Portuguese Water Dog posted this in #help-forum
Open in Discord
Avatar
Portuguese Water DogOP
Hi, what is the proper way to update state in an interval with Zustand?

I'm attempting the following; however, the component seems to rerender each second. Is there a way to prevent this?

import { useEffect } from "react";
import "./styles.css";
import { useTabStore } from "./useTabStore";
import { useShallow } from "zustand/react/shallow";

export default function App() {
  const { progress } = useTabStore(
    useShallow((s) => ({ progress: s.progress }))
  );

  useEffect(() => {
    const interval = setInterval(() => {
      useTabStore.setState((state) => {
        const newProgress = (state.progress + 1) % 101;

        if (newProgress === 100) {
          console.log("Max");
        }

        return { progress: newProgress };
      });
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  console.log({ xx: `xx ${progress}` }); // logging each second

  return (
    <div className="App">
      <p>{progress}</p>
    </div>
  );
}


I have also tried to update only primitive value, but the progress gets stuck at the number 1...
  const { progress, setProgress } = useTabStore(
    useShallow((s) => ({ progress: s.progress, setProgress: s.setProgress }))
  );

  useEffect(() => {
    const interval = setInterval(() => {
      const newProgress = (progress + 1) % 101;

      if (newProgress === 100) {
        console.log("Max");
      }

      setProgress(newProgress);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

0 Replies