Redux Todo App Guide

Updated 4 interview angles 3 min read source
On this page6
  1. Installation
  2. Core Concepts
  3. Creating a Redux Todo Store
  4. Connecting Redux to React
  5. Related
  6. Interview angle

Redux Todo App Guide

Redux is a state management library for JavaScript applications, commonly used with React. It helps manage application state in a predictable and centralized manner. This guide will walk you through building a simple Todo App using Redux in a React project.

Installation

To use Redux with React, install the necessary dependencies:

sh
npm install redux react-redux

Core Concepts

Redux follows a unidirectional data flow and consists of three key components:

1. Store

The store holds the entire application state.

2. Actions

Actions are plain JavaScript objects that describe state changes.

3. Reducers

Reducers specify how the state should change in response to actions.

Creating a Redux Todo Store

1. Defining Actions

Actions define what changes can happen in the application.

javascript
export const ADD_TODO = 'ADD_TODO';
export const TOGGLE_TODO = 'TOGGLE_TODO';

export const addTodo = (text) => ({
  type: ADD_TODO,
  payload: text
});

export const toggleTodo = (id) => ({
  type: TOGGLE_TODO,
  payload: id
});

2. Creating the Reducer

The reducer specifies how the state changes when an action is dispatched.

javascript
import { ADD_TODO, TOGGLE_TODO } from './actions';

const initialState = { todos: [] };

const todoReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TODO:
      return {
        ...state,
        todos: [...state.todos, { id: Date.now(), text: action.payload, completed: false }]
      };
    case TOGGLE_TODO:
      return {
        ...state,
        todos: state.todos.map(todo => 
          todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo
        )
      };
    default:
      return state;
  }
};

export default todoReducer;

3. Creating the Store

The store combines the reducer and provides a centralized state.

javascript
import { createStore } from 'redux';
import todoReducer from './reducers';

const store = createStore(todoReducer);
export default store;

Connecting Redux to React

Use the react-redux library to connect Redux with React components.

1. Setting up the Provider

javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

2. Using useSelector and useDispatch in the Todo App

javascript
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addTodo, toggleTodo } from './actions';

const TodoApp = () => {
  const [text, setText] = useState('');
  const todos = useSelector(state => state.todos);
  const dispatch = useDispatch();

  const handleAddTodo = () => {
    if (text.trim() !== '') {
      dispatch(addTodo(text));
      setText('');
    }
  };

  return (
    <div>
      <h2>Todo List</h2>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <button onClick={handleAddTodo}>Add Todo</button>
      <ul>
        {todos.map(todo => (
          <li 
            key={todo.id} 
            onClick={() => dispatch(toggleTodo(todo.id))} 
            style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
          >
            {todo.text}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TodoApp;

Interview angle 4

  • “What are the three principles?” - single source of truth, state is read-only and changed only by dispatching actions, and changes are made by pure reducers. Everything else in Redux follows from those.
  • “Why must reducers be pure?” - predictability, replayability and time-travel debugging. A reducer that fetches, mutates its argument, or reads Date.now() makes the same action produce different state, which breaks all three.
  • “Should you write Redux like this today?” - no. Hand-written action-type constants, action creators and switch reducers are the pattern Redux Toolkit replaced, and the official docs say so. This file is for reading existing code; write new code with createSlice.
  • “When is Redux the wrong tool?” - when the state is server data (use a query library) or local to one subtree (use component state). Putting fetched data in a global store means owning caching and invalidation yourself.