'How to run useEffect before render for authentication
I have reading component which must show only when user is loggedIn. I now redirect the user to /login page if the user is not authenticated. But during the redirect, the reading page is displayed for a few milli seconds allowing the un-authenticated user to see a flickering of the reading page during redirection.
I tried using useLayoutEffect instead of useEffect but the same flickering happens. Also tried without using useEffect or useLayoutEffect and within a function, but still the same
I get the userInfo from a global state, which gets the userInfo from the cookie. For state management I use recoil.
Reading Page: (which must be protected and if no user, redirect to login page)
function index() {
const router = useRouter();
const userInfo = useRecoilValue(userAtom); ---> userInfo is recoil global state
useLayoutEffect(() => {
if (!userInfo) {
router.push("/login?redirect=/reading");
}
}, []);
return (//some code)
Note: Adding a Loader worked, but is there any better way?
Solution 1:[1]
- Check the authentication state
- show loader based on authentication state
- Redirect the user
Solution 2:[2]
I would suggest a much better way. Instead of checking on individual pages.
You can write your Auth Check for user at route level i.e inside index.js where the React-Router is defined.
// PrivateRoute.jsx
function PrivateRoute ({component: Component, isAuth, ...rest}) {
return (
<Route
{...rest}
render={(props) => isAuth
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {userInfo} }} />}
/>
)
}
// index.jsx
.
const userInfo = useRecoilValue(userAtom);
.
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute isAuth={!!userInfo} userInfo={userInfo} path='/dashboard' component={Dashboard} />
.
.
Hope this finds it helpful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ravi Varma |
| Solution 2 | NevetsKuro |
