Full-Stack Project Development

Build a complete full-stack application from scratch including frontend, backend, database, authentication, and deployment.

advanced Backend Development 10 hours

Chapter 6: State Management

Chapter 6 of 15

Chapter 6: State Management

6.1 Global State

Effective state management is crucial for complex applications. Choose the right solution based on your needs.

// Redux Toolkit setup
import { configureStore, createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
    name: 'cart',
    initialState: { items: [] },
    reducers: {
        addItem: (state, action) => {
            state.items.push(action.payload);
        },
        removeItem: (state, action) => {
            state.items = state.items.filter(item => item.id !== action.payload);
        },
        clearCart: (state) => {
            state.items = [];
        }
    }
});

const store = configureStore({
    reducer: {
        cart: cartSlice.reducer
    }
});

6.2 Local vs Global State

// Local state - Component-specific
function Counter() {
    const [count, setCount] = useState(0);
    return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

// Global state - Shared across components
// Use Context API for simple global state
const ThemeContext = createContext();

function ThemeProvider({ children }) {
    const [theme, setTheme] = useState('light');
    return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
            {children}
        </ThemeContext.Provider>
    );
}

6.3 State Persistence

// Persist state to localStorage
function usePersistedState(key, initialValue) {
    const [state, setState] = useState(() => {
        const stored = localStorage.getItem(key);
        return stored ? JSON.parse(stored) : initialValue;
    });
    
    useEffect(() => {
        localStorage.setItem(key, JSON.stringify(state));
    }, [key, state]);
    
    return [state, setState];
}