Using TanStack Store for Global State Management Across Multiple React Components
Provide an example of using TanStack Store for global state management in a React application, showing how state can be shared and synchronized across multiple components.
import { createStore, useStore } from 'react-tanstack';
// Define the initial state
const initialState = { count: 0 };
// Create a store with the initial state
export const store = createStore(() => initialState);
This code snippet creates a global store using TanStack Store and sets an initial state with a count property. The `createStore` method from `react-tanstack` is used to create the store.
import React from 'react';
import { store } from './store';
import { useStore } from 'react-tanstack';
export function Counter() {
const [state, setState] = useStore(store);
return (
<div>
<p>{state.count}</p>
<button onClick={() => setState(prev => ({ ...prev, count: prev.count + 1 }))}>Increment</button>
</div>
);
}
This React component, `Counter`, uses the global store to display and update the count. The `useStore` hook connects the component to the store, allowing it to access the current state and update it using the `setState` function.
import React from 'react';
import { store } from './store';
import { useStore } from 'react-tanstack';
export function Display() {
const [state] = useStore(store);
return <p>Count: {state.count}</p>;
}
Another React component, `Display`, also utilizes the same global store to display the count. This demonstrates how multiple components can seamlessly share and synchronize state using TanStack Store.