Skip to content

Get started

native-state-react supports React 18.2 and React 19. Your app should already have React installed.

Terminal window
npm install native-state-react

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.

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 state.user should be already present in the existing state if state.user.name is used.

Section titled “Note that state.user should be already present in the existing state if state.user.name is used.”

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>;
}