Initializing TanStack Store in Next.js
Showcase how to install TanStack Store and set up the initial state in a Next.js application, including creating a store and defining an initial state structure.
npm install @tanstack/react-store
First, install the TanStack Store package for React (suitable for Next.js) by running this command in your terminal.
import { createStore } from '@tanstack/store-react';
const initialState = {
count: 0
};
export const counterStore = createStore({
id: 'counter',
state: () => initialState
});
Create a new JavaScript file, perhaps `store.js`, to set up your store. Import `createStore` from `@tanstack/store-react`. Define your initial state, for instance, a counter with a default value of 0. Then, create the store by invoking `createStore`, providing an id for identification and a function returning the initial state.
import { useStoreState } from '@tanstack/react-store';
import { counterStore } from './store';
function CounterComponent() {
const count = useStoreState(counterStore, state => state.count);
return <div>Counter: {count}</div>;
}
In your Next.js component, import `useStoreState` from `@tanstack/react-store` and the `counterStore` you created. Use the `useStoreState` hook to access the current state of the counter. This example shows a functional component that displays the current count value from the store.