Listening to a Value Change
Explore methods to listen for value changes in React function components beyond event handlers. Understand how to track previous values, use custom state management functions, and trigger actions when values change. This lesson helps you handle complex component interactions where changes come from multiple sources, improving control over state updates.
Monitor the change in value
We might wonder why we need to listen to a value change. Aren't the developers the ones who control the change of a value? As in the previous example, we use the event handler to change a counter. In this case, we know exactly when the value gets changed.
That's true for this case, but there are other cases. We might send a value into a child component via a prop, or there might be two components that touch a value at the same time. In either of these cases, we can lose track of the moment when the value is changed, but we still want to perform an action upon the value change. This means that we want to have the ability to listen to a value change.
Example to track changes
Let's set up one example to demonstrate this. In our "Hello World" button example, we want to know if the count value has recently changed whenever the count changes:
// Display the value of 'flag' based on the prop 'count'function Changed({ count }) {let flag = 'N';return <span>{flag}</span>;}
In the preceding Changed component, there's a count prop that is sent from its parent, say any of the "Hello" or "World" buttons that we built earlier. We want to display Y or N, depending on whether the count value has changed. We can use this Changed component in the Title component:
function Title() {// Button and title section for 'Hello'return (<><button onClick={onClickH}>+</button><h1>Hello+{countH}</h1><Changed count={countH} />{/* Button and title section for 'World' */}<button onClick={onClickW}>+</button><h1>World+{countW}</h1></>);}