-
Does anyone know whether there is a way to make zustand work together with reacts // page-store.ts
interface PageState {
page: number;
setPage: (page: number) => void;
incrementPage: () => void;
}
export const usePageStore = create<PageState>()(
persist(
(set) => ({
page: 1,
setPage: (page) => startTransition(() => set({ page })),
incrementPage: () =>
startTransition(() => set((state) => ({ page: state.page + 1 }))),
}),
{
name: "page-storage",
storage: createJSONStorage(() => sessionStorage),
}
)
);
// App.tsx
const wait = async (timeout: number) => {
await new Promise((resolve) => setTimeout(resolve, timeout));
};
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
},
},
});
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Suspense fallback={<p>Loading...</p>}>
<SuspendedDataLoading />
</Suspense>
</QueryClientProvider>
);
}
const SuspendedDataLoading = () => {
// this doesn't work
const { page, incrementPage } = usePageStore();
// this works!
//const [page, setPage] = useState(1);
//const incrementPage = () => setPage((p) => p + 1);
const { data } = useSuspenseQuery({
queryKey: ["data", page],
queryFn: async () => {
await wait(1000);
return `Page ${page}`;
},
});
const [isPending, startTransition] = useTransition();
console.log({ isPending });
const onClickNextPage = () => {
startTransition(() => {
incrementPage();
});
};
return (
<div>
<h2>{data}</h2>
<button onClick={onClickNextPage}>Next</button>
<p>{`Page ${page}`}</p>
</div>
);
}; The full CodeSandbox can be found here. Switching to |
Beta Was this translation helpful? Give feedback.
Answered by
dai-shi
May 19, 2025
Replies: 1 comment 1 reply
-
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
yss14
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try: https://github.com/zustandjs/use-zustand