I React er lyttere mekanismer, der tillader komponenter at abonnere på tilstandsændringer i andre komponenter. Når tilstanden opdateres, affyres lytter-callback med den nye værdi.
Opdatering af en child-komponents UI baseret på dens parents tilstandsændringer.
const ParentComponent = () => { const [count, setCount] = useState(0); return ( <div> <h1>Count: {count}</h1> <ChildComponent count={count} /> </div> ); }; const ChildComponent = ({ count }) => { useEffect(() => { console.log(`Count changed to ${count}`); }, [count]); // Lytter: kører når `count` ændres return <div><h2>Child Component</h2><p>The count is {count}.</p></div>; };
Her bruger ChildComponent en useEffect hook som lytter, der logger, hver gang count prop ændres.