Created
July 11, 2019 06:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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