React.js useReducer Hook Tutorial to Build Todos CRUD App for Beginners 2020

React.js useReducer Hook Tutorial to Build Todos CRUD App for Beginners 2020

 

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

 

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.

See also  React Native Tutorial to Save PDF Document to Android/IOS File System and View PDF in PDF Viewer Full Project For Beginners

 

 

 

 

 

Todos Example

 

 

Now we will look at how to build a simple todos app with useReducer hook copy paste the following code

 

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;

 

See also  Build a WebRTC Video Recorder in React.js Using react-webcam Node Library in Browser Using Javascript Full Project For Beginners

 

 

 

 

Leave a Reply