How to prevent useEffect to render twice
Hello, I have created a function which verifies the access token from the token if the token is valid or not when the component mounts and only when there is a user in the local storage and if the response is false from the backend server I am logging out the user by deleting the user from local storage and state. there is a toast notification function under the logout function, and the is alerting twice. How should I prevent that?
10 Replies
this is my function to verify the access token and callling that on useEffect
And when I removed the React strict mode than it works fine
This is a “feature” of react. It only happens in dev.
yes what if I get alert twice when I build the app
Does it? Obviously it shouldn’t do that. But I am the first to admit that my knowledge of React is limited and have never had that happen.
didn't tried yet mate, let me try once and check and thank you for the respone
I have a couple of questions.
1. Why don't you use
useCallback
instead useMemo
? Memo usually is used for values, and Callback for functions.
2. Can you share where are you firing the toast?Sir frankly speaking I didn’t even knew that and its the first time i used useMemo.
And I am firing toast at context.
SessionExpired is the function which delete user object from local storage and state too.
const SessionExpired = ()=>{
localStorage.removeItem('userLoginDetails')
dispatch({
type:'USER_LOGOUT'
})
toast.error('Sesion Expired! Please Log in again')
}
You can read more about it here: https://react.dev/reference/react/useMemo
If you can provide a reproduction of your issue in codepen or codesandbox, it would be easier to test things.
In the meantime, can you check if
userLoginDetails
is logged 4 times in verifyToken
or if the axios call is made 2 times?useMemo – React
The library for web and native user interfaces
If you have freedom or will to test something new, I encourage you to take a look to https://tanstack.com/query/latest/docs/react/overview, it will make your life easier.
Overview | TanStack Query Docs
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.
Motivation
Thanks a lot sir. I really appreciate it