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.
CodePudding user response:
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
CodePudding user response:
You have a useEffect
that runs every time name
changes.
When it runs, you're setting name
to a new value.
This changes name
and triggers the useEffect
again.
When it runs, you're setting name
to a new value.
This changes name
and triggers the useEffect
again.
And so on...
CodePudding user response:
You need to understand how useEffect
works.
you have set name
in useEffect
array dependency. So everytime the component renders name changes, as name changes your component renders again and goes into infinity loop. So you leave empty array:
const [name, setName] = useState("");
useEffect(() => {
setName(faker.name.firstName());
},[]);
return <div>{name}</div>