πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

State Management

Next.js Architecture🟒 Free Lesson

Advertisement

State Management

React Context, Zustand, URL state, and server state patterns.

Overview

State management in Next.js considers server and client state.

Key Concepts

  • Server State β€” Data from server components and fetches
  • Client State β€” UI state with Zustand or Context
  • URL State β€” Search params as state
  • Form State β€” React Hook Form or native forms
  • Cache State β€” SWR or React Query for server data

Code Examples

// Zustand store
import { create } from 'zustand';

const useCartStore = create((set) => ({
  items: [],
  addItem: (item) => set((state) => ({ items: [...state.items, item] })),
  removeItem: (id) => set((state) => ({
    items: state.items.filter(item => item.id !== id)
  })),
  clearCart: () => set({ items: [] })
}));

// URL state with search params
'use client';
import { useSearchParams, useRouter } from 'next/navigation';

function FilterControls() {
  const searchParams = useSearchParams();
  const router = useRouter();

  const setFilter = (key, value) => {
    const params = new URLSearchParams(searchParams);
    params.set(key, value);
    router.push(`?${params.toString()}`);
  };

  return (
    <div>
      <select onChange={(e) => setFilter('category', e.target.value)}>
        <option value="all">All</option>
        <option value="electronics">Electronics</option>
      </select>
    </div>
  );
}

// Combined approach
function ProductPage() {
  const cart = useCartStore();
  const searchParams = useSearchParams();
  const category = searchParams.get('category') || 'all';

  return (
    <div>
      <FilterControls />
      <ProductList category={category} />
      <Cart items={cart.items} />
    </div>
  );
}

Practice

Build a shopping cart with Zustand, URL filters, and server-side data.

⭐

Premium Content

State Management

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement