pmndrs / zustand

🐻 Bear necessities for state management in React

Home Page:https://zustand-demo.pmnd.rs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The value I save to storage with persist is delayed when the page refreshes.

aydinvivik opened this issue · comments

Summary

When I refresh the page with the value I saved to localstorage with persist, it takes the old value for 1 second and then shows the new value. Is there any way to avoid this 1 second delay?

My example code is below;

use-store.js

'use client';

import { useState, useEffect } from 'react';

const useStore = (store, callback) => {
  const result = store(callback);
  const [data, setData] = useState();

  useEffect(() => {
    setData(result);
  }, [result]);

  return data;
};

export default useStore;

use-template.js

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

const initialStates = {
  templateStatus: false,
};

const useTemplate = create(
  persist(
    (set) => ({
      ...initialStates,
      setTemplateStatus: () => {
        set((state) => ({ templateStatus: !state.templateStatus }));
      },
    }),
    {
      name: 'template-status',
    }
  )
);

export default useTemplate;

component.js

'use client';

import useStore from './store/use-store';
import useTemplate from './store/use-template';

export default function Home() {
  const templateStatus = useStore(
    useTemplate,
    (state: any) => state.templateStatus
  );
  const setTemplateStatus = useTemplate((state) => state.setTemplateStatus);
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div className="mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-4 lg:text-left">
        <p>template status: {templateStatus ? 'true' : 'false'}</p>
        <button onClick={setTemplateStatus}>change template status</button>
      </div>
    </main>
  );
}

Link to reproduction

https://stackblitz.com/edit/stackblitz-starters-jjsutv?file=app%2Fpage.tsx

Check List

Please do not ask questions in issues.

  • I've already opened a discussion before opening this issue, or already discussed in other media.

Please include a minimal reproduction.

Please check this if you're filing an issue regarding TypeScript.

  • I've read the typescript guide, in particular that create is to be used as create<T>()(...) and not create<T>(...).