Created
February 9, 2022 11:23
-
-
Save tomsoderlund/0b7a92afc21dfa4df123acf7bdfaa773 to your computer and use it in GitHub Desktop.
React Context and State rolled into one
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
/* | |
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