Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useEffects without dependency arrays #74

Open
rooberrydev opened this issue Nov 10, 2022 · 0 comments
Open

useEffects without dependency arrays #74

rooberrydev opened this issue Nov 10, 2022 · 0 comments

Comments

@rooberrydev
Copy link

useEffect(() => {
async function fetchReviews() {
let awsReviews = await DataStore.query(Reviews, (item) =>
item.EventID("eq", eventId)
);
setReviewsApi(awsReviews);
}
const fetchInterval = setInterval(fetchReviews, 1000);
return () => clearInterval(fetchInterval);
});

useEffect(() => {
const getAccommodation = async () => {
const accommodation = await DataStore.query(Accommodation, (item) =>
item.EventID("eq", eventId)
);
setAccommodation(accommodation[0]);
};
getAccommodation();
});

useEffects without a second argument with an array of dependencies can run in an infinite loop - since they run whenever the component re-renders, and if you're setting state within the useEffect, then the component re-renders, which re-runs the useEffect, sets state again, re-renders the component, re-runs the useEffect... on and on

to avoid this - I tend to follow these rules

  1. if I want it to run only once (the first time the component renders) - use an empty dependency array
useEffect(()=>{
  doStuff()
},[]})
  1. If I do something based on a state value, add it to the dependency array so the effect only runs when the state changes between re-renders
@patdel0 patdel0 moved this to Core in Away Days Nov 11, 2022
@AlexPD93 AlexPD93 moved this from Core to Unexpected behaviour in Away Days Nov 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Unexpected behaviour
Development

No branches or pull requests

1 participant