Skip to content

Instantly share code, notes, and snippets.

@aashish-chaubey
Created July 11, 2019 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aashish-chaubey/60359dee4ccdc1df846c0b039b5bebfa to your computer and use it in GitHub Desktop.
Save aashish-chaubey/60359dee4ccdc1df846c0b039b5bebfa to your computer and use it in GitHub Desktop.
Making use of `useReducer` React hook for managing the state of the functional component
import React, { useReducer } from 'react';
const reducer = (state, action) => {
switch(action.type) {
case 'add': {
return [
...state,
{
id: Date.now(),
text: '',
completed: false
}
]
}
default: {
return state;
}
}
}
function Todo() {
const [state, dispatch] = useReducer(reducer, []);
return (
<>
<h1>Todo App</h1>
<button onClick={() => dispatch({ type: 'add' })}>Create</button>
{ state.map(item => (
<div key={item.id}>{item.id}</div>
))}
</>
);
}
export default Todo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment