useReducer() Hook - Web dev Simplified
Tags: javascript, webdev, react, beginners
Published: 2023-01-01 11:40:14

## Part 1:-

**App.js Code :-**

``` react
import { useReducer } from "react";

const initialState = [
    {
        id: 1,
        label: 'aksh',
        Checked: false
    },
    {
        id: 2,
        label: 'rudra',
        Checked: false
    }
]

const reducer = (state) => {
    return [
        {
            id: 1,
            label: 'aksh1',
            Checked: true
        }
    ]

}

const App = () => {
    const [todos, dispatch] = useReducer(reducer, initialState)

    const handleOnChange = () => {
        dispatch();
    }
    return (
        <>
            <h1> Hello World </h1>

            {todos.map((todo) => {
                console.log(todo);
                return <label key={todo.id}>
                    <input type="checkbox" checked={todo.Checked} onChange={handleOnChange} />
                    {todo.label}
                </label>
            })}
        </>
    )
}

export default App;
```

**Output :-**

![Output 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lc6h8krzsc6ccvof8oz9.png)


![Output 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c94u72jirky2yg9wr5v9.png)

---

## Part 2:-

**App.js Code :-**

``` react


import { useState, useReducer } from 'react'

const ACTIONS = {
    ADD_TODO: 'add-todo',
    TOGGLE_TODO: 'toggle-todo'
};

function reducer(todos, action) {
    switch (action.type) {
        case ACTIONS.ADD_TODO:
            if (todos === null) {
                return [newTodo(todos, action.payload.name)]
            }
            else {
                return [...todos, newTodo(todos, action.payload.name)]
            }
        case ACTIONS.TOGGLE_TODO:
            return todos.map((todo) => {
                if (todo.id === action.payload.id) {
                    return { ...todo, complete: !todo.complete };
                }
                else {
                    return todo;
                };
            })
        case 'blank':
            return null;
        default:
            return todos;
    }
};

function newTodo(prevTodos, name) {
    if (prevTodos === null) {
        localStorage.setItem('localtodos', JSON.stringify([{ id: Date.now(), name: name, complete: false }]));
    }
    else {
        localStorage.setItem('localtodos', JSON.stringify([...prevTodos, { id: Date.now(), name: name, complete: false }]));
    }
    return { id: Date.now(), name: name, complete: false }
}

const App = () => {
    const [name, setName] = useState("");
    const [todos, dispatch] = useReducer(reducer, JSON.parse(localStorage.getItem("localtodos"))
    );

    const handleSubmit = (e) => {
        e.preventDefault();
        dispatch({ type: ACTIONS.ADD_TODO, payload: { name: name } });
        setName("");
    };

    const handleChange = async (id) => {
        await dispatch({ type: ACTIONS.TOGGLE_TODO, payload: { id: id } })
        let newTodo = todos.map((todo) => {
            if (todo.id === id) {
                return { ...todo, complete: !todo.complete };
            }
            else {
                return todo;
            };
        })
        localStorage.setItem("localtodos", JSON.stringify(newTodo));
    };

    return (
        <>
            <form onSubmit={handleSubmit}>
                <input type="text" value={name} onChange={e => setName(e.target.value)} />
            </form>

            {todos === null ? '' : <input type="button" onClick={() => {
                localStorage.clear();
                dispatch({ type: 'blank' });
            }} value="cancel" />}

            {todos === null ? <h1> Add Some Notes to Preview </h1> : todos.map((todo) => {
                return <h3 style={{backgroundColor: todo.complete === false ? 'cyan' : ''}} key={todo.id} >
                    <input type="checkbox" checked={todo.complete} onChange={() => { handleChange(todo.id) }} />
                    {todo.name}
                    <br />
                </h3>
            })
            }
        </>
    )
};

export default App;
```

**Output **

![Output 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpsp6w74gbzzrib74mrt.png)

Thank You.
You can follow us on:
[Youtube ](https://www.youtube.com/c/ULTIMATEPROGRAMMING)
[Instagram](https://www.instagram.com/full_stack_web_developer1/)