Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

rerender in react to get a new name everytime I refreshed?

why this code give me infinite loop?

import { useState, useEffect } from 'react';
import './style.css';
import { faker } from '@faker-js/faker';

export default function App() {
  const data = faker.name.firstName();
  const [name, setName] = useState(data);

  useEffect(() => {
    setName(faker.name.firstName());
  }, [name]);

  return <div>{name}</div>;
}

https://stackblitz.com/edit/react-ts-6ept5o?file=App.tsx

I want a new generated name using faker everytime i refreshed the page.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Well there’s several problems here. Firstly, React state isn’t persisted when you refresh the page. To do that you’d have to web storage or some library to help store when changing/refreshing the page. So you don’t need an effect here nor to worry about getting new fake data on refresh, you will.

Also, when a functional component re-renders, the entire function gets run again. So this: const data = faker.name.firstName(); gets run every time you render. If you want to use it as an initial state, use the function argument to useState which runs it once on page load: useState(() => faker.name.firstName());

Finally, in regards to the infinite loop, your effect has name as a dependency, but inside it you also set name state. So you’re getting a loop.

Component renders:
-> effect runs, setting name state
-> set state triggers re-render with new name
-> new name triggers effect, since name is a dependency
-> effects sets name state to new value
-> set state triggers re-render

and so on. But in this case, you don’t actually need an effect at all, given reasons mentioned above

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading