Skip to main content

REACT js State Management

Table of Contents

  1. [State Management]
  2. Redux State Management

React components manage their local state using Hooks, primarily useState and useReducer. For global state, React's Context API is often used, or external libraries like Redux, Zustand, or Jotai are integrated. React 19 introduces new hooks like useOptimistic, useActionState, and useFormStatus to streamline async operations and form handling.

// React state with useState hook
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // [currentState, setStateFunction]

const increment = () => {
setCount(count + 1); // Or setCount(prevCount => prevCount + 1); for functional updates
};

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}

what is state management

Redux

slice | Store |

Zustand

Zustand is a state management library for React applications. It provides a simple and lightweight way to manage state within your components without the need for complex setups or external dependencies.

Zustand is built on the concept of stores, which are containers for your application state. Each store represents a specific slice of your application's state and can hold any kind of data, such as primitives, objects, or arrays.

To use Zustand, you first need to create a store. This is typically done using the create function from the zustand package. Here's an example:

import create from 'zustand';

const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));

function Counter() {
const { count, increment, decrement } = useStore();

return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}

In this example, the create function is used to define a store with an initial state of { count: 0 } and two actions: increment and decrement. The useStore hook is then used within the Counter component to access the state and actions from the store.

Whenever the increment or decrement functions are called, Zustand automatically updates the state and re-renders the component.

Zustand also allows you to create derived state and subscribe to changes in the store. It provides a flexible and intuitive API for managing state in your React applications without the need for more complex state management solutions like Redux.

Note that this example demonstrates a basic usage of Zustand, and there are more advanced features and patterns available, such as middleware and selectors, which can be explored in the official documentation: https://github.com/pmndrs/zustand