react-auth-simple
React authentication Component with React Hooks
See this demo APP: https://codesandbox.io/s/react-auth-simple-demo-0y89v
Install
npm i react-auth-simple
Usage
react-auth-simple
provides a simple way to manage user login state for SPA(Single Page Application).
In SPA, we usually use a client side router, such as react-router. And we may have many client-side-rendered pages, some of them need user authentication
, and some don't require.
So, when users navigate between our pages, these two cases are common:
- User is navigating to page B from page A, where A can be viewed without login in, whereas B requires user
authentication
. In this case, we need to show ourLoginModal
, or redirect to theLoginPage
- After user has logged in, all the pages can share this global
authentication
state
react-auth-simple
encourages developer to use LoginModal
to show the login page, rather than a LoginPage
.
Demo Code
You're talking too much, just show me code
; // Home page can be visited without login // AccountCenter requires user login// Usually checking current user login state is an async operation// So we should render some temporary view when we don't get login state yet// use HOC to protect our AccountCenter; // LoginModal is where user input username and password, set global user after login success // initUser is called to check use login state when page load// You may call an API, or read localStorage ; // Finally our App, we're using react-router for simplicity