Blog>
Snippets

Integrating TanStack Store in a React Functional Component

Demonstrate how to use TanStack Store for state management in a React functional component, including the setup of a basic store and utilizing the `useStoreState` hook to access state within the component.
import { createStore, useStoreState } from '@tanstack/react-store';
First, import createStore to create the store, and useStoreState to access the state within a React component.
const store = createStore({
  id: 1,
  name: 'TanStack Store Example'
});
Create a basic store with initial state. This example store holds an ID and a name.
function MyComponent() {
  // Access store state in the component
  const name = useStoreState(store, state => state.name);

  return (
    <div>
      <p>{name}</p>
    </div>
  );
}
In the React functional component, use the useStoreState hook to access the 'name' from our store's state and render it.