Search code examples
reactjszustand

set timeout when update zustand state


I try to update zustand state use set timeout without other hooks

const useCustom = create(set => ({
  isAction: false,
  onAction: value =>
    set(prev => {
      return { isAction: true };
      setTimeout(() => {
        return { isAction: false };
      }, 100);
    }),
}));

Is there a solution for this?


Solution

  • If you set setTimeout in this way , it should work as you expect

    const useCustom = create(set => ({
        isAction: false,
        onAction: () => {
           set({ isAction: true });
           setTimeout(() => {
             set((state) => ({ isAction: false }));
           }, 100);
        },
    }));