Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Created October 20, 2020 16:31
Show Gist options
  • Select an option

  • Save davidsharp/dc737fb265d8b44ba727dc6ebdee129a to your computer and use it in GitHub Desktop.

Select an option

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
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}
@davidsharp

Copy link
Copy Markdown
Author

used something like:

import {useExample} from 'example-hook'
const App = props => {
  const [example, setExample, immutablySetExample] = useExample()
  const deepSetProp = () => immutablySetResource(draft=>{draft.foo.bar.baz++})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment