Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Unstated Next sample code
    Unstated Next React state management lightweight state management React Context API React Hooks state container managing state in React


Unstated Next sample code


Unstated Next is a lightweight state management library for React that uses React's built-in Context API and Hooks. Here is a concise example of how to use Unstated Next to manage state across multiple components:

Creating a State Container

First, we create a state container using the `createContainer` function from Unstated Next:

javascript
import { createContainer } from 'unstated-next';

function useCounter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return { count, increment, decrement };
}

const CounterContainer = createContainer(useCounter);

The `useCounter` function defines the state and logic for a counter, and `createContainer` wraps it to create a reusable state container.

Using the State Container

Now we can use the `CounterContainer` in our components:

javascript
function CounterDisplay() {
  const { count } = CounterContainer.useContainer();
  return <p>Count: {count}</p>;
}

function CounterControls() {
  const { increment, decrement } = CounterContainer.useContainer();
  return (
    <div>
      <button onClick={decrement}>-</button>
      <button onClick={increment}>+</button>
    </div>
  );
}

function App() {
  return (
    <CounterContainer.Provider>
      <CounterDisplay />
      <CounterControls />
    </CounterContainer.Provider>
  );
}

The `CounterDisplay` and `CounterControls` components both use the `useContainer` method to access the state and actions from the `CounterContainer`. The `CounterContainer.Provider` component wraps the app and provides the shared state to its children.

This way, the state is managed centrally in the `useCounter` function, and any component that needs access to the counter state or actions can simply use the `useContainer` method to get what it needs.[1][2][3]

Citations:
[1] https://github.com/jamiebuilds/unstated-next
[2] https://css-tricks.com/managing-state-in-react-using-unstated-next/
[3] https://blog.logrocket.com/state-management-with-unstated-next/
[4] https://www.geeksforgeeks.org/unstated-next-lightweight-state-management-library-for-reactjs-part-3-shopping-cart/
[5] https://www.npmjs.com/package/unstated-next/v/1.0.0?activeTab=readme