Skip to content

Instantly share code, notes, and snippets.

@zaguiini
Last active June 21, 2023 08:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaguiini/f5d343a7579bac8c530beabf781677c9 to your computer and use it in GitHub Desktop.
Save zaguiini/f5d343a7579bac8c530beabf781677c9 to your computer and use it in GitHub Desktop.
import React from 'react'
const Store = React.createContext()
const useStore = () => React.useContext(Store)
const reducer = (state, action) => {
switch(action.type) {
case 'ADD_TODO':
return { ...state, todos: [...state.todos, action.payload] }
default:
return state
}
}
const initialValue = {
todos: [],
}
const App = () => {
const [value, dispatch] = React.useReducer(reducer, initialValue)
return (
<Store.Provider value={{ ...value, dispatch }}>
<TodoList />
</Store.Provider>
)
}
const TodoList = () => {
const { todos, dispatch } = useStore()
const add = (text) => {
dispatch({
action: 'ADD_TODO',
payload: text,
})
}
return (
<div>
{todos.map((todo, idx) => <div key={idx}>{todo}</div>)}
<AddTodo onAdd={add} />
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment