Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 &&}</div>
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

This comment has been minimized.

Copy link
Owner Author

tomsoderlund commented Jan 11, 2020

Shared state using React Hooks and Context

Inspired by Sambhav Gore:

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
You can’t perform that action at this time.