Skip to content

Instantly share code, notes, and snippets.

@marcincodes
Last active May 27, 2021 12:40
Show Gist options
  • Save marcincodes/345ac41d2e24baec28b4ee93392cbe1b to your computer and use it in GitHub Desktop.
Save marcincodes/345ac41d2e24baec28b4ee93392cbe1b to your computer and use it in GitHub Desktop.
Setting state in parent lead to multiple useEffect runs
function Root() {
const [increment, setIncrement] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setIncrement((inc) => inc + 1);
}, 3000);
return () => clearInterval(interval);
}, []);
return (
<Fragment>
Live counter: {increment}
<br />
<ArticlesWithMutipleRerenders />
</Fragment>
);
}
function ArticlesWithMultipleRerenders() {
const [articles, setArticles] = useState([]);
const db = DBConnection();
useEffect(() => {
console.count("get articles");
db.getArticles().then(setArticles);
}, [db]);
return (
<Fragment>
{articles.map((article) => (
<span key={article.title}>{article.title} </span>
))}
</Fragment>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment