Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
How to prevent infinite loop in useEffect using Object from Redux store as dependency?

I am relatively new to React, so probably it will be an easy answer for some of you.

I have bumped into a little problem, I have solved it, but it doesn't seem to be perfect as React Eslint is not happy.

My web-app is using React-Redux at the front and Node-Express-Mongo at the back. So, I have a functional component (screen/page), and whenever logged in user visits it, it needs to update user data state in Redux store to make sure it matches current data in database.

However, not registered and not logged in users also can visit that page, then obviously that database check is not needed.

I get user data as userInfo object from Redux:

const userLogin = useSelector((state) => state.userLogin);
const { loading: loadingUser, error: errorUser, userInfo } = userLogin;

Then, when component renders useEffect() hook shoots, I dispatch an action to get user data from backend (DB) using JWT token.

useEffect(() => {
    //update user details in case if access to restricted services changes
    if (userInfo && userInfo.token) {
      dispatch(refreshUser(userInfo.token));
    }
    // eslint-disable-next-line
  }, []);

As you can see I kept dependency array empty, and disabled it for eslint to keep Mr Eslint happy.

So far this is the only way I can make it work. If I put userInfo into dependency array - it creates infinite loop, because as we know {}==={} always returns false.

If I get rid of userInfo from useEffect() and keep just userInfo.token, but then it creates an error userInfo is undefined whenever user is not logged in

Of course I can populate Redux store with some initial state of empty userInfo or empty userInfo.token, but that seems to be unnecessary hassle. I also tried to put useEffect inside if (userInfo){} statement, but that was just silly, as useEffect() should stay at the top level...

As it is now, it does what I need it to do - runs just once as the component (page) loads.

So my question is: Is it OK to leave it like that or there must be some elegant solution?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!