Skip to content

Instantly share code, notes, and snippets.

@TautvydasDerzinskas
Created October 20, 2021 11:07
Show Gist options
  • Save TautvydasDerzinskas/b8f347cbef7d0e2c172ca1301061aef6 to your computer and use it in GitHub Desktop.
Save TautvydasDerzinskas/b8f347cbef7d0e2c172ca1301061aef6 to your computer and use it in GitHub Desktop.
// 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