Skip to content

Instantly share code, notes, and snippets.

@reoxb
Created September 15, 2024 03:29
Show Gist options
  • Save reoxb/dd608d83d6cccb01b2d182d2158ac516 to your computer and use it in GitHub Desktop.
Save reoxb/dd608d83d6cccb01b2d182d2158ac516 to your computer and use it in GitHub Desktop.
React - Context API
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';
const UserProfile = () => {
const { user, logout } = useContext(AuthContext);
return (
<div>
<h2>Welcome, {user ? user.name : 'Guest'}</h2>
{user && <button onClick={logout}>Logout</button>}
</div>
);
};
export default UserProfile;
import React, { createContext, useState } from 'react';
// Create the AuthContext
const AuthContext = createContext();
// Create a provider component
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
// Function to handle login
const login = (userData) => {
// Perform login logic and set the user state
setUser(userData);
};
// Function to handle logout
const logout = () => {
// Perform logout logic and reset the user state
setUser(null);
};
// Value object to be passed to consuming components
const authContextValue = {
user,
login,
logout,
};
return (
<AuthContext.Provider value={authContextValue}>
{children}
</AuthContext.Provider>
);
};
export { AuthContext, AuthProvider };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment