Welcome folks today in this post we will be looking at react usereducer hook tutorial to build todo app
. All the source code of application will be given below. A step by step youtube video is also shown below.
Get Started
Now to get started you need to create the react.js project simply and inside your app.js
file copy paste the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import React, { useReducer } from "react"; function reducer(state,action){ switch(action.type){ case "increment": return state + 1; case "decrement": return state - 1 default: return state; } } export default function App() { const [count,dispatch] = useReducer(reducer,0) function increment(){ dispatch({type:'increment'}) } function decrement(){ dispatch({type:'decrement'}) } return ( <div className="App"> <div>Count:{count}</div> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } |
In this block of code we are using theuseReducer
hook to manage state instead of useState Hook. Here we have two buttons of increment and decrement which increases or decreases the value of counter and we display the value of counter. This is a very basic way by which we can use useReducer hook inside our react.js application.
Todos Example
Now we will look at how to build a simple todos app with useReducer hook copy paste the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import React, { useReducer, useState } from "react"; function reducer(state, action) { switch (action.type) { case "add-todo": return { todos: [...state.todos, { text: action.text, completed: false }], todoCount: state.todoCount + 1 }; case "toggle-todo": return { todos: state.todos.map((t, idx) => idx === action.idx ? { ...t, completed: !t.completed } : t ), todoCount: state.todoCount }; case "delete-todo": return { todos: state.todos.filter((t, idx) => idx !== action.idx), todoCount: state.todoCount - 1 }; default: return state; } } const App = () => { const [{ todos, todoCount }, dispatch] = useReducer(reducer, { todos: [], todoCount: 0 }); const [text, setText] = useState(); return ( <div> <form onSubmit={e => { e.preventDefault(); dispatch({ type: "add-todo", text }); setText(""); }} > <input value={text} onChange={e => setText(e.target.value)} /> </form> <div>number of todos: {todoCount}</div> {todos.map((t, idx) => ( <div key={t.idx} onClick={() => dispatch({ type: "toggle-todo", idx })} onDoubleClick={() => dispatch({type:"delete-todo",idx})} style={{ textDecoration: t.completed ? "line-through" : "" }} > {t.text} {idx} </div> ))} <pre>{JSON.stringify(todos,null,2)}</pre> </div> ); }; export default App; |