intermediate#next.js#react#todo list
Building a Todo List App with Next.js and React Hooks
Learn how to build a todo list app using Next.js and React Hooks, and understand how to manage state and side effects.
Introduction to React Hooks
React Hooks are a way to use state and other React features in functional components. In this tutorial, we will build a todo list app using Next.js and React Hooks.
Step 1: Creating the Todo List Component
Let's create a new component called TodoList.js in the components directory:
// components/TodoList.js
import { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState('');
const handleAddTodo = () => {
setTodos([...todos, newTodo]);
setNewTodo('');
};
return (
<div>
<input type='text' value={newTodo} onChange={(e) => setNewTodo(e.target.value)} />
<button onClick={handleAddTodo}>Add Todo</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</div>
);
}
export default TodoList;
Step 2: Integrating the Todo List Component with Next.js
Let's create a new page called todo.js in the pages directory and integrate the TodoList component:
// pages/todo.js
import TodoList from '../components/TodoList';
function Todo() {
return (
<div>
<h1>Todo List</h1>
<TodoList />
</div>
);
}
export default Todo;
Step 3: Running the Application
To run the application, navigate to the project directory and use the following command:
npm run dev
This will start the development server, and you can access your todo list app at http://localhost:3000/todo.