Languages
[Edit]
EN

React - simple login / logout service

3 points
Created by:
sienko
743

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.

 

Alternative titles

  1. React - simple login / logout logic with shared context
  2. React - simple login / logout logic with useContext
  3. React - auth service
  4. React - authentication service
1
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