In React, listeners are mechanisms that allow components to subscribe to state changes in other components. When the state updates, the listener callback fires with the new value.
Updating a child component's UI based on its parent's state changes.
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]); // Listener: runs when `count` changes
return <div><h2>Child Component</h2><p>The count is {count}.</p></div>;
};
Here, ChildComponent uses a useEffect hook as a listener that logs whenever the count prop changes.