Building a simple to-do list app with React and local storage

Building a Simple To-Do List App with React and Local Storage

In today's fast-paced world, productivity tools like to-do list apps have become essential for managing tasks efficiently. If you’ve ever wanted to create your own to-do list application, this article will guide you through building a simple yet effective to-do list app using React and local storage. By the end of this tutorial, you’ll have a fully functional app that stores your tasks even after refreshing the browser.

What is React?

React is a popular JavaScript library for building user interfaces, especially single-page applications where you need a fast and interactive experience. It allows developers to create reusable UI components, making it an excellent choice for dynamic applications like a to-do list.

Why Use Local Storage?

Local storage is a web storage solution that allows you to store data directly in the user's browser. It provides a simple way to save key-value pairs, making it ideal for persisting your to-do list items across page refreshes. Unlike cookies, local storage has a larger storage capacity and does not get sent with HTTP requests, which enhances performance.

Setting Up Your Development Environment

Before we dive into the code, let’s set up our development environment. You’ll need:

  • Node.js: Ensure you have Node.js installed. You can download it from nodejs.org.
  • Create React App: This tool sets up a new React project with a default configuration.

To create a new React application, open your terminal and run:

npx create-react-app todo-app
cd todo-app

Now that your environment is set up, let’s start developing our to-do list app!

Step 1: Creating the Basic Structure

Next, we’ll set up the basic structure of our app. Open the src folder and edit the App.js file.

import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [tasks, setTasks] = useState([]);
  const [task, setTask] = useState('');

  useEffect(() => {
    const savedTasks = JSON.parse(localStorage.getItem('tasks'));
    if (savedTasks) {
      setTasks(savedTasks);
    }
  }, []);

  const addTask = () => {
    if (task) {
      const newTasks = [...tasks, task];
      setTasks(newTasks);
      localStorage.setItem('tasks', JSON.stringify(newTasks));
      setTask('');
    }
  };

  const removeTask = (index) => {
    const newTasks = tasks.filter((_, i) => i !== index);
    setTasks(newTasks);
    localStorage.setItem('tasks', JSON.stringify(newTasks));
  };

  return (
    <div className="App">
      <h1>To-Do List</h1>
      <input 
        type="text" 
        value={task} 
        onChange={(e) => setTask(e.target.value)} 
        placeholder="Add a new task" 
      />
      <button onClick={addTask}>Add</button>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>
            {task} 
            <button onClick={() => removeTask(index)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Explanation of the Code

  1. State Management: We’re using React's useState to manage the tasks and the current input value.
  2. Local Storage: The useEffect hook retrieves tasks from local storage when the component mounts.
  3. Adding Tasks: The addTask function updates the task list and local storage when a new task is added.
  4. Removing Tasks: The removeTask function filters out the selected task and updates the state and local storage.

Step 2: Styling the App

To make our app visually appealing, let’s add some basic styles. Open App.css and add the following styles:

.App {
  text-align: center;
}

input {
  margin: 10px;
  padding: 10px;
  width: 200px;
}

button {
  padding: 10px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
}

These styles will center the content and give some spacing to the input and buttons, making it user-friendly.

Step 3: Testing the App

Now it’s time to test your app! Start your React app by running:

npm start

This command will launch your app in the default web browser. You should see an input field where you can add tasks, and a list displaying the tasks. Tasks will persist even after refreshing the page, thanks to local storage.

Troubleshooting Common Issues

Issue 1: Tasks Not Saving

  • Solution: Ensure that you are correctly setting and retrieving items from local storage. Check your browser's developer tools (Console) for any error messages.

Issue 2: App Not Rendering

  • Solution: Double-check your component imports and ensure that the useEffect and useState hooks are correctly implemented.

Conclusion

Congratulations! You’ve built a simple to-do list app using React and local storage. This project not only demonstrates how to handle state and effects in React but also how to interact with the browser’s local storage to persist data.

Next Steps

To enhance your to-do list app, consider adding features such as:

  • Editing tasks: Allow users to modify existing tasks.
  • Task completion: Implement a checkbox to mark tasks as complete.
  • Filters: Add options to view all tasks, completed tasks, or pending tasks.

By continuing to build on your skills, you can enhance this simple application into a more complex productivity tool. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.