Languages
[Edit]
EN

React - simple login / logout service

3 points
Created by:
sienko
593

In this article, we would like to show you how to create a simple login/logout service in React.

In below example, we create an AuthenticationContext object which let us share a context between child components. Context lets us share some information across components without using props - all child components have access to the parent context.

Using AuthenticationContext.Provider we are able to share with all children authenticationService object. To access authenticationService object in any child it is necessary to call useContext(AuthenticationContext).

  • UserMenu functional component is the first component that uses our AuthenticationContext initialized in App. With button elements and their onClick methods we can login or logout our user by updating AuthenticationContext.
  • SiteNavbar component is the second component that uses AuthenticationContext.
    It displays our user using getUser() method from our authenticationService and renders UserMenu component.
  • User data is stored inside state in App component to force re-rendering for all components when user data are changed - user is logged in or logged out.
// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const AuthenticationContext = React.createContext();

const UserMenu = () => {
    const authenticationService = React.useContext(AuthenticationContext);
  	const handleLoginClick = () => authenticationService.loginUser('john');
    const handleLogoutClick = () => authenticationService.logoutUser();
    return (
      <>
        <button onClick={handleLoginClick}>Login John!</button>
        <button onClick={handleLogoutClick}>Logout John!</button>
      </>
    );
};

const SiteNavbar = () => {
    const authenticationService = React.useContext(AuthenticationContext);
    return (
      <div>
        <span>{authenticationService.getUser()}</span>
        <UserMenu />
      </div>
    );
};

const App = () => {
  const [user, setUser] = React.useState(null);
  const authenticationService = {
      getUser: () => user,
      loginUser: (user) => {
          //TODO: Replace setUser with AJAX request to server
          setUser(user);
          return true;
      },
      logoutUser: () => {
          //TODO: Replace setUser with AJAX request to server
          setUser(null);
          return true;
      }
      // other methods ...
  };
  return (
    <AuthenticationContext.Provider value={authenticationService}>
      <SiteNavbar />
    </AuthenticationContext.Provider>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

Alternative titles

  1. React - simple login / logout logic with shared context
  2. React - simple login / logout logic with useContext
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - login / logout service
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join