Last active
May 13, 2021 01:50
-
-
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
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
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> | |
) | |
} |
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
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 |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
ExampleHook.js
)Note:
UserContext.js
is the important file here, the rest are just usage examples.