Created
October 20, 2020 16:31
-
-
Save davidsharp/dc737fb265d8b44ba727dc6ebdee129a to your computer and use it in GitHub Desktop.
An example of a React context hook, but with an extra immer-powered immutable setter
This file contains hidden or 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' | |
| import immer from 'immer'; | |
| const ExampleStateContext = createContext() | |
| const ExampleDispatchContext = createContext() | |
| const ExampleProvider = ({children}) => { | |
| const [example, setExample] = useState(null) | |
| return ( | |
| <ExampleStateContext.Provider value={example}> | |
| <ExampleDispatchContext.Provider value={setExample}> | |
| {children} | |
| </ExampleDispatchContext.Provider> | |
| </ExampleStateContext.Provider> | |
| ) | |
| } | |
| const useExampleState = () => { | |
| const context = useContext(ExampleStateContext) | |
| if (context === undefined) { | |
| throw new Error('useExampleState must be used within a ExampleProvider') | |
| } | |
| return context | |
| } | |
| const useExampleDispatch = () => { | |
| const context = useContext(ExampleDispatchContext) | |
| if (context === undefined) { | |
| throw new Error('useExampleDispatch must be used within a ExampleProvider') | |
| } | |
| return context | |
| } | |
| const useImmutableExampleDispatch = () => { | |
| const example= useExampleState() | |
| const dispatch = useExampleDispatch() | |
| return fn => dispatch(immer(example,fn)) | |
| } | |
| const useExample = () => [useExampleState(), useExampleDispatch(), useImmutableExampleDispatch()] | |
| export {ExampleProvider, useExample} |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
used something like: