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

106
Views
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 answers
Answer question

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 Report
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!