🔄 Redux Todo App - Complete Project

Live Working App + Complete Code + Hinglish Explanation

🎯

Live Todo App (Working!)

0
Total
0
Active
0
Completed
📝

No todos yet!

Add your first todo above to get started

💻

Complete Code

🎯 Store Setup - Hinglish Explanation

Ye kya hai? Redux store ek central database hai jahan app ka saara data store hota hai.

Kaise kaam karta hai?

  • configureStore Redux Toolkit ka function hai jo store create karta hai
  • Isme hum apne saare reducers add karte hain
  • Redux DevTools automatically enable ho jata hai
  • Middleware (Redux Thunk) by default included hai

Real example: Ye ek bank vault jaisa hai - saara paisa (data) ek jagah safe rehta hai!

store.js - Redux Store Configuration
// store.js
import { configureStore } from '@reduxjs/toolkit';
import todoReducer from './todoSlice';

// Store create karo - ye app ka central database hai
const store = configureStore({
  reducer: {
    // Yahan saare reducers add karo
    todos: todoReducer,
    // Aur reducers add kar sakte ho:
    // user: userReducer,
    // cart: cartReducer,
  },
  // Redux DevTools automatically enabled!
  // Middleware (Thunk) by default included!
});

export default store;

🎯 Todo Slice - Hinglish Explanation

Slice kya hai? Slice ek feature ka complete code hai - reducer + actions sab ek jagah!

Is slice mein kya hai?

  • initialState: Starting data - empty array aur 'all' filter
  • reducers: Functions jo state ko change karte hain
  • addTodo: Naya todo add karta hai
  • toggleTodo: Todo ko complete/incomplete mark karta hai
  • deleteTodo: Todo delete karta hai
  • setFilter: Filter change karta hai (all/active/completed)

Magic: Redux Toolkit mein "mutating" code likh sakte ho! state.push() safe hai kyunki Immer library internally immutability handle karti hai!

todoSlice.js - Todo Logic
// todoSlice.js
import { createSlice } from '@reduxjs/toolkit';

// Initial state - app start hone pe ye data hoga
const initialState = {
  items: [], // Saare todos yahan
  filter: 'all' // Current filter
};

// Slice create karo - reducer + actions ek saath!
const todoSlice = createSlice({
  name: 'todos', // Slice ka naam
  initialState,
  reducers: {
    // Naya todo add karo
    addTodo(state, action) {
      // Redux Toolkit mein "mutating" code safe hai!
      // Immer library internally immutability handle karti hai
      state.items.push({
        id: Date.now(), // Unique ID
        text: action.payload, // Todo text
        completed: false // Initially incomplete
      });
    },

    // Todo ko toggle karo (complete/incomplete)
    toggleTodo(state, action) {
      const todo = state.items.find(t => t.id === action.payload);
      if (todo) {
        todo.completed = !todo.completed; // Toggle!
      }
    },

    // Todo delete karo
    deleteTodo(state, action) {
      // Filter se naya array banao (without deleted todo)
      state.items = state.items.filter(t => t.id !== action.payload);
    },

    // Filter set karo
    setFilter(state, action) {
      state.filter = action.payload; // 'all', 'active', or 'completed'
    },

    // Completed todos clear karo
    clearCompleted(state) {
      state.items = state.items.filter(t => !t.completed);
    }
  }
});

// Actions export karo - components mein use karenge
export const { 
  addTodo, 
  toggleTodo, 
  deleteTodo, 
  setFilter, 
  clearCompleted 
} = todoSlice.actions;

// Reducer export karo - store mein use karenge
export default todoSlice.reducer;

🎯 Component - Hinglish Explanation

Component kya karta hai? Ye UI render karta hai aur user interactions handle karta hai.

Important hooks:

  • useSelector: Store se data read karta hai. Jab data change hota hai, component re-render hota hai
  • useDispatch: Actions dispatch karne ke liye. Ye ONLY way hai state change karne ka

Selectors:

  • selectFilteredTodos: Current filter ke according todos return karta hai
  • selectStats: Total, active, completed count calculate karta hai

Flow: User clicks button → dispatch(action) → Reducer updates state → Component re-renders with new data!

TodoApp.jsx - React Component
// TodoApp.jsx
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { 
  addTodo, 
  toggleTodo, 
  deleteTodo, 
  setFilter, 
  clearCompleted 
} from './todoSlice';

function TodoApp() {
  // Local state for input field
  const [input, setInput] = useState('');

  // Get dispatch function - actions dispatch karne ke liye
  const dispatch = useDispatch();

  // Store se data read karo using selectors
  const todos = useSelector(state => state.todos.items);
  const filter = useSelector(state => state.todos.filter);

  // Filtered todos calculate karo
  const filteredTodos = todos.filter(todo => {
    if (filter === 'active') return !todo.completed;
    if (filter === 'completed') return todo.completed;
    return true; // 'all'
  });

  // Stats calculate karo
  const stats = {
    total: todos.length,
    active: todos.filter(t => !t.completed).length,
    completed: todos.filter(t => t.completed).length
  };

  // Add todo handler
  const handleAddTodo = () => {
    if (input.trim()) {
      dispatch(addTodo(input)); // Action dispatch!
      setInput(''); // Clear input
    }
  };

  return (
    <div>
      {/* Input Section */}
      <input
        value={input}
        onChange={e => setInput(e.target.value)}
        placeholder="Enter todo..."
      />
      <button onClick={handleAddTodo}>Add</button>

      {/* Filter Buttons */}
      <button onClick={() => dispatch(setFilter('all'))}>All</button>
      <button onClick={() => dispatch(setFilter('active'))}>Active</button>
      <button onClick={() => dispatch(setFilter('completed'))}>Completed</button>

      {/* Stats */}
      <div>Total: {stats.total}</div>
      <div>Active: {stats.active}</div>
      <div>Completed: {stats.completed}</div>

      {/* Todo List */}
      {filteredTodos.map(todo => (
        <div key={todo.id}>
          <input
            type="checkbox"
            checked={todo.completed}
            onChange={() => dispatch(toggleTodo(todo.id))}
          />
          <span>{todo.text}</span>
          <button onClick={() => dispatch(deleteTodo(todo.id))}>
            Delete
          </button>
        </div>
      ))}
    </div>
  );
}

export default TodoApp;

🎯 App Setup - Hinglish Explanation

Provider kya hai? Provider ek wrapper component hai jo Redux store ko puri app mein available karata hai.

Kaise kaam karta hai?

  • Provider ko root level pe wrap karo
  • Store prop mein apna Redux store pass karo
  • Ab koi bhi child component useSelector aur useDispatch use kar sakta hai!

Real example: Provider ek WiFi router jaisa hai - ek baar setup karo, phir puri ghar (app) mein internet (store) available hai!

index.js - App Entry Point
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import store from './store';
import TodoApp from './TodoApp';

// Root element
const root = ReactDOM.createRoot(
  document.getElementById('root')
);

// App render karo with Redux Provider
root.render(
  <React.StrictMode>
    {/* Provider se puri app ko wrap karo */}
    {/* Store prop mein Redux store pass karo */}
    <Provider store={store}>
      <TodoApp />
    </Provider>
  </React.StrictMode>
);

📦 Package.json Dependencies

Ye packages install karne honge:

package.json
{
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.1.0",
    "@reduxjs/toolkit": "^1.9.5"
  }
}

// Install command:
// npm install react react-dom react-redux @reduxjs/toolkit
🔄

Redux Data Flow - Step by Step

Complete Redux Flow (Hinglish Explanation)

1

User Interaction (UI Event)

Kya hota hai: User button click karta hai ya form submit karta hai

Example: User "Add Todo" button pe click karta hai

2

Dispatch Action

Kya hota hai: Component dispatch(action) call karta hai

Example: dispatch(addTodo('Buy milk'))

Action object: { type: 'todos/addTodo', payload: 'Buy milk' }

3

Middleware (Optional)

Kya hota hai: Action reducer tak pahunchne se pehle middleware se guzarta hai

Example: Logger middleware action ko console mein log karta hai

Use case: API calls, logging, analytics

4

Reducer Processes Action

Kya hota hai: Reducer action ko dekh kar state update karta hai

Example: addTodo reducer naya todo items array mein add karta hai

Important: Reducer pure function hai - no side effects!

5

Store Updates

Kya hota hai: Redux store new state save karta hai

Example: Store mein todos array update ho jata hai with new todo

Note: Old state replace nahi hota, new state object create hota hai

6

Components Re-render

Kya hota hai: Store subscribers ko notify karta hai

Example: TodoApp component re-render hota hai with new todos

Optimization: Sirf wo components re-render hote hain jinko selected data change hua hai

7

UI Updates

Kya hota hai: Screen pe naya data dikhta hai

Example: Naya todo list mein appear hota hai

Result: User ko updated UI dikhta hai! 🎉

✅ Key Takeaways (Important Points)

1. One-way data flow: Data hamesha ek hi direction mein flow hota hai - predictable aur debug karna easy!

2. Single source of truth: Saara data ek jagah (store) mein hai - no confusion!

3. State is read-only: State ko directly change nahi kar sakte - sirf actions dispatch karke!

4. Pure reducers: Reducers pure functions hain - same input = same output, no side effects!

5. Redux Toolkit FTW: Redux Toolkit use karo - less code, more power! 💪

🎓 Learning Path (Next Steps)

Beginner level complete! Ab kya seekhein?

  • Async operations: createAsyncThunk se API calls handle karna
  • Selectors: createSelector se memoized selectors banana
  • Middleware: Custom middleware banana
  • Normalization: createEntityAdapter se complex state manage karna
  • TypeScript: Type-safe Redux code likhna
  • Testing: Redux logic ko test karna