Skip to content

Instantly share code, notes, and snippets.

Created November 2, 2019 18:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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);
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