Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Created February 9, 2022 11:23
Show Gist options
  • Save tomsoderlund/0b7a92afc21dfa4df123acf7bdfaa773 to your computer and use it in GitHub Desktop.
Save tomsoderlund/0b7a92afc21dfa4df123acf7bdfaa773 to your computer and use it in GitHub Desktop.
React Context and State rolled into one
/*
Usage:
import { ItemContextProvider } from 'hooks/useItem'
<ItemContextProvider
item={item}
>
<ComponentThatUsesItem />
</ItemContextProvider>
and inside ComponentThatUsesItem:
import { useItem } from 'hooks/useItem'
const { item } = useItem()
*/
import React, { createContext, useContext, useState } from 'react'
export const ItemContext = createContext()
export const ItemContextProvider = (props) => {
// Use State to keep the values. Initial values are obtained from ItemContextProvider’s props.
const [item, setItem] = useState(props.item)
// Make the context object (i.e. the “API” for Item)
const itemContext = {
item,
// updateItem,
// deleteItem
}
// Pass the value in Provider and return
return <ItemContext.Provider value={itemContext}>{props.children}</ItemContext.Provider>
}
export const { Consumer: ItemContextConsumer } = ItemContext
export const useItem = () => useContext(ItemContext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment