Blog>
Snippets

Setting Up User Authentication Flow with React Context

Provides an example of setting up a basic user authentication flow using React Context API for state management and securing routes.
import React, { createContext, useContext, useState } from 'react';

// Context creation
const AuthContext = createContext(null);

// Custom hook to use context
export const useAuth = () => useContext(AuthContext);
This code snippet creates an AuthContext using React's createContext and exports a custom hook useAuth for easy access to the context.
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  // Simulate login
  const login = (username) => {
    // Authentication logic here
    setUser({ name: username });
  };

  // Simulate logout
  const logout = () => {
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};
Defines an AuthProvider component that uses the AuthContext to provide a user object and login/logout functions to its children.
import { useAuth } from './AuthProvider';

const ProtectedRoute = ({ children }) => {
  const { user } = useAuth();

  if (!user) {
    // Redirect to login page
    return <div>Please login to see this page.</div>;
  }

  return children;
};
Creates a ProtectedRoute component that checks if a user is logged in. If not, it displays a message asking the user to login.
import React from 'react';
import ReactDOM from 'react-dom';
import { AuthProvider } from './AuthProvider';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
Wraps the entire React application in an AuthProvider to ensure that the authentication context is accessible throughout the app.