{"id":7281,"date":"2025-06-25T23:32:40","date_gmt":"2025-06-25T23:32:39","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7281"},"modified":"2025-06-25T23:32:40","modified_gmt":"2025-06-25T23:32:39","slug":"build-a-todo-app-with-react-and-localstorage-6","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/build-a-todo-app-with-react-and-localstorage-6\/","title":{"rendered":"Build a Todo App with React and LocalStorage"},"content":{"rendered":"<h1>Build a Todo App with React and LocalStorage<\/h1>\n<p>Are you looking to build your first React application and make it interactive? A Todo app is an excellent project for beginners to understand the essential concepts of React, including state management, component lifecycle, and local storage manipulation. In this blog post, we&#8217;ll guide you step-by-step on how to create a simple yet functional Todo app, where users can add, delete, and mark tasks as completed, all while utilizing LocalStorage to persist the data. Let&#8217;s dive in!<\/p>\n<h2>What is React?<\/h2>\n<p>React is an open-source JavaScript library developed by Facebook for building user interfaces, especially for single-page applications. Its main goal is to simplify the process of building rich, interactive UIs by breaking them into smaller reusable components. It allows developers to create large web applications that can change data without reloading the page, providing a seamless user experience.<\/p>\n<h2>What is LocalStorage?<\/h2>\n<p>LocalStorage is part of the Web Storage API that enables web applications to store data in the user&#8217;s browser. It allows for the storage of key-value pairs, with no expiration, making it a solid choice for managing application state that needs to persist across browser sessions. In our Todo app, we will use LocalStorage to save the list of tasks so that they remain available even after the page is refreshed.<\/p>\n<h2>Setting Up Your React App<\/h2>\n<p>To get started, you&#8217;ll need a React development environment. If you haven&#8217;t already set up one, you can do so with Create React App, a convenient CLI tool.<\/p>\n<pre><code>npx create-react-app my-todo-app\ncd my-todo-app\nnpm start\n<\/code><\/pre>\n<p>This will create a new directory called <strong>my-todo-app<\/strong> and start a local development server. Open your browser and navigate to <strong>http:\/\/localhost:3000<\/strong> to see your newly created React app in action!<\/p>\n<h2>Project Structure<\/h2>\n<p>Your project should have a simple structure. For our Todo app, we&#8217;ll primarily work with <strong>src\/App.js<\/strong>. You can also create a new file called <strong>src\/Todo.js<\/strong> to keep the Todo component separate for better organization.<\/p>\n<h2>Creating the Todo Component<\/h2>\n<p>Let\u2019s create a basic Todo component that allows us to add tasks. In <strong>Todo.js<\/strong>, we&#8217;re going to define a functional component that includes an input field for adding tasks and a button to submit them.<\/p>\n<pre><code>import React, { useState, useEffect } from 'react';\n\nconst Todo = () =&gt; {\n    const [task, setTask] = useState('');\n    const [todos, setTodos] = useState([]);\n\n    useEffect(() =&gt; {\n        const storedTodos = JSON.parse(localStorage.getItem('todos'));\n        if (storedTodos) {\n            setTodos(storedTodos);\n        }\n    }, []);\n\n    useEffect(() =&gt; {\n        localStorage.setItem('todos', JSON.stringify(todos));\n    }, [todos]);\n\n    const handleSubmit = (e) =&gt; {\n        e.preventDefault();\n        if (!task) return;\n        setTodos([...todos, { text: task, isCompleted: false }]);\n        setTask('');\n    };\n\n    const handleDelete = (index) =&gt; {\n        const newTodos = todos.filter((_, i) =&gt; i !== index);\n        setTodos(newTodos);\n    };\n\n    const handleComplete = (index) =&gt; {\n        const newTodos = todos.map((todo, i) =&gt;\n            i === index ? { ...todo, isCompleted: !todo.isCompleted } : todo\n        );\n        setTodos(newTodos);\n    };\n\n    return (\n        <div>\n            <h2>Todo List<\/h2>\n            \n                 setTask(e.target.value)}\n                    placeholder=\"Enter a new task\"\n                \/&gt;\n                <button type=\"submit\">Add Task<\/button>\n            \n            <ul>\n                {todos.map((todo, index) =&gt; (\n                    <li style=\"{{\">\n                        {todo.text}\n                        <button> handleComplete(index)}&gt;Toggle Complete<\/button>\n                        <button> handleDelete(index)}&gt;Delete<\/button>\n                    <\/li>\n                ))}\n            <\/ul>\n        <\/div>\n    );\n};\n\nexport default Todo;\n<\/code><\/pre>\n<h2>Integrating Todo Component into App<\/h2>\n<p>Now that our Todo component is ready, we need to integrate it into our main application file, <strong>App.js<\/strong>. Import the Todo component and include it in the render method.<\/p>\n<pre><code>import React from 'react';\nimport Todo from '.\/Todo';\n\nfunction App() {\n    return (\n        <div>\n            <h1>My Todo App<\/h1>\n            \n        <\/div>\n    );\n}\n\nexport default App;\n<\/code><\/pre>\n<h2>Handling State with LocalStorage<\/h2>\n<p>Our Todo component manages its state using React&#8217;s <strong>useState<\/strong> and <strong>useEffect<\/strong> hooks. When the component mounts for the first time, it reads the Todo list from LocalStorage and sets it into the component state. When the state changes (e.g., adding or deleting a task), we save the new list back to LocalStorage.<\/p>\n<h2>Styling Your App<\/h2>\n<p>While functionality is important, it\u2019s also essential to have a visually appealing UI. You can apply some basic CSS to style your Todo App. Create a new file called <strong>App.css<\/strong> and add the following styles:<\/p>\n<pre><code>body {\n    font-family: Arial, sans-serif;\n    background-color: #f4f4f4;\n    padding: 20px;\n}\n\nh1 {\n    text-align: center;\n}\n\nform {\n    display: flex;\n    justify-content: center;\n    margin: 20px 0;\n}\n\ninput {\n    padding: 10px;\n    font-size: 16px;\n    width: 300px;\n}\n\nbutton {\n    padding: 10px;\n    margin-left: 10px;\n    font-size: 16px;\n    cursor: pointer;\n}\n\nul {\n    list-style-type: none;\n    padding: 0;\n}\n\nli {\n    background: white;\n    margin: 10px 0;\n    padding: 15px;\n    display: flex;\n    justify-content: space-between;\n}\n\nbutton {\n    background-color: #007BFF;\n    color: white;\n    border: none;\n    border-radius: 3px;\n}\n\nbutton:hover {\n    background-color: #0056b3;\n}\n<\/code><\/pre>\n<p>Don\u2019t forget to import your CSS file in <strong>App.js<\/strong>:<\/p>\n<pre><code>import '.\/App.css';\n<\/code><\/pre>\n<h2>Running Your Todo App<\/h2>\n<p>With everything in place, your Todo app should now be functional. Save your changes and navigate to <strong>http:\/\/localhost:3000<\/strong>. You can now add tasks, mark them as completed, and delete them. Additionally, refreshing the page will not reset your tasks, thanks to LocalStorage.<\/p>\n<h2>Conclusion<\/h2>\n<p>Congratulations! You have successfully built a Todo app using React and LocalStorage. This project has introduced you to essential concepts in React\u2014component creation, state management, and utilizing the Web Storage API. As you become more comfortable with React, feel free to expand upon this project. Consider adding features like editing tasks, filtering completed tasks, or even user authentication.<\/p>\n<p>We hope you found this guide helpful and that it encourages you to learn more about React and web development!<\/p>\n<h2>Further Resources<\/h2>\n<ul>\n<li><a href=\"https:\/\/reactjs.org\/docs\/getting-started.html\" target=\"_blank\">React Documentation<\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Window\/localStorage\" target=\"_blank\">MDN Web Docs &#8211; LocalStorage<\/a><\/li>\n<li><a href=\"https:\/\/css-tricks.com\/snippets\/css\/a-guide-to-flexbox\/\" target=\"_blank\">CSS Tricks &#8211; Flexbox Guide<\/a><\/li>\n<\/ul>\n<p>Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Build a Todo App with React and LocalStorage Are you looking to build your first React application and make it interactive? A Todo app is an excellent project for beginners to understand the essential concepts of React, including state management, component lifecycle, and local storage manipulation. In this blog post, we&#8217;ll guide you step-by-step on<\/p>\n","protected":false},"author":98,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[398],"tags":[224],"class_list":{"0":"post-7281","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-react","7":"tag-react"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7281","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/98"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7281"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7281\/revisions"}],"predecessor-version":[{"id":7284,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7281\/revisions\/7284"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7281"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7281"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7281"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}