Integrating TanStack Store with React
Demonstrate setting up TanStack Store in a React application, including the instantiation of the store and using a custom React hook to read and update the store state.
import { createStore, useStore } from '@tanstack/react-store';
// Define your store's initial state
const initialState = { counter: 0 };
// Create a store instance
export const store = createStore({
initialState
});
This code snippet shows how to import the necessary functions from TanStack's React store library, set up an initial state for the store, and then create the store itself with this initial state. The initial state in this example consists of a simple counter set to 0.
import { store } from './path/to/your/store';
export function useCounter() {
const [state, setState] = useStore(store);
function increment() {
setState(prevState => ({ ...prevState, counter: prevState.counter + 1 }));
}
function decrement() {
setState(prevState => ({ ...prevState, counter: prevState.counter - 1 }));
}
return { counter: state.counter, increment, decrement };
}
Here, a custom hook called `useCounter` is defined, which utilizes TanStack's `useStore` hook to access and update the store's state. This custom hook provides `increment` and `decrement` functions to manipulate the `counter` value in the store, and returns the current `counter` value along with these functions for easy access and update.
import React from 'react';
import { useCounter } from './path/to/your/hooks';
const CounterComponent = () => {
const { counter, increment, decrement } = useCounter();
return (
<div>
<p>Counter: {counter}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
};
export default CounterComponent;
In this final snippet, a React functional component called `CounterComponent` is defined, making use of the custom `useCounter` hook. This component displays the `counter` state and provides buttons to invoke the `increment` and `decrement` functions, allowing the user to modify the counter's value.