Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pubudu-ranasinghe
Created November 2, 2019 18:17
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 pubudu-ranasinghe/064f080bb433f86a3c2f69e683344637 to your computer and use it in GitHub Desktop.
Save pubudu-ranasinghe/064f080bb433f86a3c2f69e683344637 to your computer and use it in GitHub Desktop.
react-context-example-09
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