An effect with [query] runs only when query changes. Type in the box, then change the theme, and compare.
React · beginner · 7 min · 26 steps · free
import { useState, useEffect } from 'react';
export default function SearchBox() {
const [query, setQuery] = useState('');
const [theme, setTheme] = useState('light');
useEffect(() => {
console.log(`searching for "${query}"`);
}, [query]);
return (
<div className={theme}>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Theme: {theme}</button>
</div>
);
}<SearchBox> for the first time: it calls the SearchBox function.useState runs for the first time, so React stores the starting value for query and returns it: "".useState runs for the first time, so React stores the starting value for theme and returns it: "light".[query]: after each render, React runs it only if query changed.SearchBox returns JSX: a description of what the screen should show, <div className="light">…</div>. React has not changed the page yet.onChange handler.setQuery(e.target.value) does not change query right away: React queues the update and will render again. In this call query is still "".<SearchBox> again (render 2): it calls SearchBox once more, from the top.useState returns the value React has kept for query: "react". The starting value is only used on the first render.useState returns the value React has kept for theme: "light". The starting value is only used on the first render.useEffect does not run the effect now. React runs it after the page has been updated, and again only when a dependency changes.SearchBox returns JSX: a description of what the screen should show, <div className="light">…</div>. React has not changed the page yet.theme will change.setTheme(theme === 'light' ? 'dark' : 'light') does not change theme right away: React queues the update and will render again. In this call theme is still "light".<SearchBox> again (render 3): it calls SearchBox once more, from the top.useState returns the value React has kept for query: "react". The starting value is only used on the first render.useState returns the value React has kept for theme: "dark". The starting value is only used on the first render.SearchBox returns JSX: a description of what the screen should show, <div className="dark">…</div>. React has not changed the page yet.Answer: Once, after the first render
Answer: It compares with Object.is
← useEffect: Code That Runs After Render · Effect Cleanup →