Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Last active May 13, 2021 01:50
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomsoderlund/232c7bc69f90070a03daa75692e3fc56 to your computer and use it in GitHub Desktop.
Save tomsoderlund/232c7bc69f90070a03daa75692e3fc56 to your computer and use it in GitHub Desktop.
Shared state using React Hooks and Context, to allow sharing of state between multiple components or hooks
import React, { useContext } from 'react'
import { UserContext, UserContextProvider } from './UserContext'
export default (props) => {
const [user, setUser] = useContext(UserContext)
return (
<UserContextProvider user={null}>
<div>User name: {user && user.name}</div>
</UserContextProvider>
)
}
import { UserContext } from './UserContext'
export const useUserSubscription = function () {
const [user, setUser] = useContext(UserContext)
const setUserSubscription = (subscription) => setUser(Object.assign({}, user, { subscription }))
return [userSubscription, setUserSubscription]
}
export default useUserSubscription
import React, { createContext, useState } from 'react'
export const UserContext = createContext()
// The Provider must be wrapping your app/page that will use UserContext
export const UserContextProvider = props => {
// Use State to keep the values. Initial values are obtained from UserContextProvider’s props.
const [user, setUser] = useState(props.user)
// Make the context object (or array)
const userContext = [user, setUser]
// Pass the value in Provider and return
return <UserContext.Provider value={userContext}>{props.children}</UserContext.Provider>
}
// The Consumer can be used instead of the hook useContext(UserContext), e.g. in class components
export const { Consumer: UserContextConsumer } = UserContext
@tomsoderlund
Copy link
Author

tomsoderlund commented Jan 11, 2020

Shared state using React Hooks and Context

Inspired by Sambhav Gore: https://www.codementor.io/@sambhavgore/an-example-use-context-and-hooks-to-share-state-between-different-components-sgop6lnrd

This a very powerful React Hooks pattern, allowing:

  • Multiple components to share the same State
  • Build hooks that are derived from other hooks, e.g. in this example when User is changed, so does the User’s Subscriptions (ExampleHook.js)

Note: UserContext.js is the important file here, the rest are just usage examples.

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