Next js

State Management In Next Js

What is State Management?

  • State refers to data that determines what the UI looks like.

  • State management means organizing, updating, and sharing that data across components.


Types of State

Type Description Scope
Local State State inside a single component (e.g., form inputs) Component only
Global State Shared across many components (e.g., user auth) Entire app or large parts
Server State Data fetched from a backend or API App-wide or page-wide
URL State Data in the URL query params or path Across pages or routes

Managing State Locally

  • Use React hooks like useState and useReducer.

Example:

jsx
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}


Managing Global State


1. React Context API

  • Built-in way to share state without prop drilling.

  • Good for light global state like themes or user info.

Example:

jsx
import { createContext, useContext, useState } from 'react';

const AuthContext = createContext();

export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
return (
<AuthContext.Provider value={{ user, setUser }}>
{children}
</AuthContext.Provider>
);
}

export function useAuth() {
return useContext(AuthContext);
}


2. State Management Libraries

  • Redux: Popular and powerful, supports complex global state.

  • Recoil: Simplifies shared state with atoms and selectors.

  • Zustand, MobX, Jotai: Other lighter alternatives.


Managing Server State

  • Use libraries like React Query, SWR for caching and syncing remote data.

  • Example: SWR

jsx
import useSWR from 'swr';

function Profile() {
const { data, error } = useSWR('/api/user', fetcher);
if (error) return <div>Failed to load</div>;
if (!data) return <div>Loading...</div>;
return <div>Hello, {data.name}</div>;
}


Summary Table

State Type Management Method When to Use
Local State useState, useReducer Component-specific data
Global State Context API, Redux, Recoil Shared data across app
Server State React Query, SWR Fetching/caching remote data
URL State Next.js router query params Syncing UI with URL

Leave a Reply

Your email address will not be published. Required fields are marked *