Created
October 20, 2021 11:07
-
-
Save TautvydasDerzinskas/b8f347cbef7d0e2c172ca1301061aef6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 1. Create context file (contexts) | |
import React from 'react'; | |
export const UserContext = React.createContext<{ | |
name: string; | |
surname: string; | |
}>({ | |
name: '', | |
surname: '', | |
}); | |
// 2. Create provider with context values and wrap with it the app | |
import { UserContext } from "~Contexts/user"; | |
ReactDOM.render( | |
<React.StrictMode> | |
<Provider store={store}> | |
<UserContext.Provider value={{ name: "Vardenis", surname: "Pavardenis" }}> | |
<App /> | |
</UserContext.Provider> | |
</Provider> | |
</React.StrictMode>, | |
document.getElementById("root") | |
); | |
// 3. Create hook for easy access of the context | |
import React from 'react'; | |
import { UserContext } from '~Contexts/user'; | |
export const useUserInfo = () => { | |
const userData = React.useContext(UserContext); | |
return userData; | |
}; | |
// 4. Use the hook to access context data | |
import { useUserInfo } from "~Hooks/user"; | |
export const Comments: FC<unknown> = () => { | |
const { name, surname } = useUserInfo(); | |
.... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment