🔴 Redux Basics

Predictable State Management

What is Redux?

Redux is a predictable state container for JavaScript apps. It helps you manage global state using a single store and pure reducer functions.

🎯 Core Concepts

// Three principles of Redux:
// 1. Single source of truth: One store for entire app
// 2. State is read-only: Only change state via actions
// 3. Changes are made with pure functions: Reducers

// Store: Holds the state tree
// Action: Plain object describing what happened
// Reducer: Pure function that returns new state
// Dispatch: Send actions to store

🏗️ Setup Redux

// Install
// npm install redux react-redux

// store.js
import { createStore } from 'redux';
import { Provider } from 'react-redux';

// Initial state
const initialState = {
  count: 0,
  user: null
};

// Reducer
function rootReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    case 'SET_USER':
      return { ...state, user: action.payload };
    default:
      return state;
  }
}

// Create store
const store = createStore(rootReducer);

// Wrap app with Provider
function App() {
  return (
    
      
    
  );
}

🎣 Using Redux in Components

import { useSelector, useDispatch } from 'react-redux';

function Counter() {
  // Read state
  const count = useSelector(state => state.count);
  
  // Get dispatch function
  const dispatch = useDispatch();
  
  return (
    

{count}

); } // Action creators const increment = () => ({ type: 'INCREMENT' }); const decrement = () => ({ type: 'DECREMENT' }); const setUser = (user) => ({ type: 'SET_USER', payload: user }); function Counter() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return (
); }

🔄 Multiple Reducers

import { combineReducers } from 'redux';

// Counter reducer
function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// User reducer
function userReducer(state = { user: null }, action) {
  switch (action.type) {
    case 'LOGIN':
      return { user: action.payload };
    case 'LOGOUT':
      return { user: null };
    default:
      return state;
  }
}

// Combine reducers
const rootReducer = combineReducers({
  counter: counterReducer,
  user: userReducer
});

// Access state
const count = useSelector(state => state.counter.count);
const user = useSelector(state => state.user.user);

🎯 Key Takeaways