Blog>
Snippets

Initializing TanStack Store in React Native

Demonstrate how to install and configure TanStack Store in a React Native project, showing the setup of an initial store with a simple state structure.
npm install @tanstack/store-react
First, install the TanStack Store package for React projects. Run this command in your React Native project's root directory.
// store.js
import { createStore } from '@tanstack/store-react';

export const store = createStore({
  initialState: { count: 0 },
  name: 'counterStore'
});
Create a new file named 'store.js'. In this file, import createStore from '@tanstack/store-react' and use it to create a new store with an initial state. This example creates a simple counter store.
// App.js
import React from 'react';
import { useStore } from '@tanstack/store-react';
import { store } from './store';

const App = () => {
  const [state, actions] = useStore(store);

  return (
    <>
      <Text>Count: {state.count}</Text>
      <Button title="Increment" onPress={() => actions.setState({ count: state.count + 1 })} />
    </>
  );
};

export default App;
In your application (e.g., 'App.js'), import the useStore hook from '@tanstack/store-react' along with the store you created. This example demonstrates how to display and update the state in a React Native component.