Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda