Last active
November 4, 2022 20:27
-
-
Save crazy4groovy/6dbdd61354b4597bf12f4c5b8e3a9ffb to your computer and use it in GitHub Desktop.
context + hook pattern (ReactJS)
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 { UserProvider } from "./context" | |
import { Component } from "./component" | |
export default function App() { | |
return ( | |
<UserProvider> | |
<h1>Context App</h1> | |
<Component /> | |
<br /> | |
<Component /> | |
</UserProvider> | |
) | |
} |
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 { useUser } from "./hook" | |
export function Component() { | |
const { name, setName } = useUser() | |
const onClick = () => | |
setName(Math.random().toString().slice(2)) | |
return <button onClick={onClick}>{name}</button> | |
} |
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 { createContext, useState } from "react" | |
const useUserInit = (_name = "unknown") => { | |
const [name, setName] = useState(_name) | |
return { name, setName } | |
} | |
export const UserContext = createContext({}) | |
export function UserProvider({ children }) { | |
const user = useUserInit() | |
return ( | |
<UserContext.Provider value={user}> | |
{children} | |
</UserContext.Provider> | |
) | |
} | |
export function TestUserProvider({ children, value }) { | |
return ( | |
<UserContext.Provider value={value}> | |
{children} | |
</UserContext.Provider> | |
) | |
} | |
export function TestContextProvider({ children, Context, value }) { | |
return ( | |
<Context.Provider value={value}> | |
{children} | |
</UserContext.Provider> | |
) | |
} |
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 { useContext } from "react" | |
import { UserContext } from "./context" | |
export const useUser = () => useContext(UserContext) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://codesandbox.io/s/react-context-hook-ejh2kn