Get started
Before you begin
Section titled “Before you begin”native-state-react supports React 18.2 and React 19. Your app should already have React installed.
Install
Section titled “Install”npm install native-state-reactInitialize the store
Section titled “Initialize the store”Render <Root> near the top of your app and pass the initial state you want to share. For a typical app, do this once:
import React from 'react';import { createRoot } from 'react-dom/client';import { Root } from 'native-state-react';import App from './App';
const initialState = { user: { name: 'Mary' }, cart: { itemCount: 0 },};
createRoot(document.getElementById('root')).render( <React.StrictMode> <Root initial={initialState}> <App /> </Root> </React.StrictMode>);initial is optional and defaults to an empty object. It is read only the first time <Root> initializes the module-level store. See store lifetime and server rendering before mounting multiple roots or rendering on a server.
Read, initialise and update a value
Section titled “Read, initialise and update a value”Call useNativeState inside a component to get a value and its setter:
import { useNativeState } from 'native-state-react';
export function Profile() { const [name, setName] = useNativeState('state.user.name',"Abraham");
return ( <section> <p>Hello, {name}</p> <button onClick={() => setName('George')}>Rename</button> </section> );}The path points/create an existing or new value in the state. When setName receives a new value, components subscribed to that path are notified. Paths can also address array items, for example state.todos[0].done.
Note that
Section titled “Note that state.user should be already present in the existing state if state.user.name is used.”state.usershould be already present in the existing state ifstate.user.nameis used.
Read without writing
Section titled “Read without writing”For a component that only needs to display state, use useNativeSelector:
import { useNativeSelector } from 'native-state-react';
export function CartCount() { const count = useNativeSelector('state.cart.itemCount'); return <span>Items: {count}</span>;}What to read next
Section titled “What to read next”- State paths explains path syntax and why parent objects must exist.
- Read and write state covers setter behavior and initialization.
- Choose a selector explains how subscriptions and re-renders work.