Created
November 2, 2019 18:17
-
-
Save pubudu-ranasinghe/064f080bb433f86a3c2f69e683344637 to your computer and use it in GitHub Desktop.
react-context-example-09
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, { createContext, useState, useContext } from "react"; | |
export const TodoContext = createContext(); | |
const initialItems = [ | |
"Extract todo state to todo context", | |
"Implement todo provider" | |
]; | |
// We wrap the provider in a nice little component | |
// which will hold the state and provide methods to | |
// update the state | |
function TodoProvider(props) { | |
const [items, setItems] = useState(initialItems); | |
function add(item) { | |
setItems([...items, item]); | |
} | |
function remove(index) { | |
const copy = [...items]; | |
copy.splice(index, 1); | |
setItems(copy); | |
} | |
const todoData = { items, add, remove }; | |
return <TodoContext.Provider value={todoData} {...props} />; | |
} | |
// Here we create a custom hook that allows us to consume | |
// the todo context | |
function useTodoContext() { | |
return useContext(TodoContext); | |
} | |
export { TodoProvider, useTodoContext }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment