Introduction:
Session Implementation is essential for managing user authentication and preserving user-specific data in React applications. It allows the application to keep track of a user’s login status, ensuring it can provide personalized experiences and secure access to authorized users.

Local storage for session management:
Use the localstorage.setItem and localstorage.getItem functions to store and retrieve the isLoggedIn state.
const[isLoggedIn,setIsLoggedIn]=useState(localStorage.getItem(‘isLoggedIn’) ===’true’);

Initialize isLoggedIn State:

Initialize the isLoggedIn state using the value retrieved from local storage. Update the state when the User logs in or logs out.

Redirect on login:

Implement handleLoginSuccess function, to set the isLoggedIn state to true when a user successfully logs in. Redirect the User to the dashboard upon successful login

const handleLognSuccess = () =>{
setIsLoggedIn(true);

localstorage.setItem(‘isLoggedIn’,’true’);

history.push(‘/dashboard’);
};

Note: make sure to call the handleLoginSuccess function in the Login API Response upon successful login.

Logout functionality:

Create handleLogout function to set the isLoggedIn state to false when the user logs out. clear the local storage to remove session data.

Redirect the user to the login page after logging out.

const handleLogout = () =>{
setIsLoggedIn(false);
//clear session data from local storage

localstorage.removeItem(‘isLoggedIn’);

//Redirect to login page

history.push(‘/’);

};

Conditional Rendering:

conditionally render Navbar and Sidenav based on the isLoggedIn state.show navigation menus and user-specific content when the user is logged in.

{isLoggedIn && (

<>
<Navbar handleDraweropen={handleDraweropen} handleLogout={handleLogout} />

<Sidenav mobileopen={mobileopen} handleDraweropen={handleDraweropen} handleDrawerClose={handleDrawerClose} isLoggedIn={isLoggedIn} handleLogout={handleLogout} />
</>

)}


Protecting Routes:

Implement a PrivateRoute component to protect specific routes for authenticated users. Use React Router to ensure that only authenticated users can access certain pages.

import { Route, Redirect } from ‘react-router-dom’;

function PrivateRoute({ component: Component, isLoggedIn, …rest }) {

return (

{…rest}

render={(props) => isLoggedIn ? <Component {…props} /> : <Redirect to=”/” />

}

/>

);

}

// Usage;
<PrivateRoute exact path=”/dashboard” component={Dashboard} isLoggedIn={isLoggedIn} />

Conclusion:

Session management in React provides the foundation for secure authentication and personalized user experiences.

Leave a Reply