Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Inifnite render error when setting value via useState inside a useEffect only when testing

I have the following simple component where I am just looking to set a value at the start.

Thus trying to set the value inside useEffect.

I have simplified the component to be minimal here.
As long as I try to set the value via useState, it throws following error.

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

It it not the externalFunction. Issue is with using the useState setter itself since even setting it to true throws same error.

Why is this an issue?

If I try to do a counter inside here, I only enter useEffect once when I comment out setValid.
But if I call setValid, I enter useEffect about 25 times before erroring.

How could I rectify this issue. I need to set this value via useState for use further down in the component. Please advice.

Code:

export const MyComponent = () => {
  const [valid, setValid] = React.useState(undefined);
  React.useEffect(() => {
    setValid(externalFunction());
    // setValid(true); // same error
  }, []);

  return <MyComponent />;
};

This works fine when I run it. The error comes from running following test.

import { shallow } from 'enzyme';
const render = (props) => shallow(
    <MyComponent
        {...props}
    />
);

it('should render', () => {
    const renderedModule = render();
    expect(renderedModule).toMatchSnapshot();
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The example as given does not cause a recursive render. See this sandbox.

If you need to set the initial value of a state to a function return value, though, setState can take a function to call for its initial value:

export const MyComponent = () => {
  const [valid, setValid] = useState(externalFunction);
  // Or more verbosely:
  // const [valid, setValid] = useState(() => externalFunction());

  return <div>test</div>;
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda