The first line of defense to avoid unnecessary re-renders is using React.memo. React.memo will skip rendering the component, and reuse the last rendered result.
Let's wrap all the child components in React.memo.


We managed to save 3 components from re-rendering on change of Name input field, but still Address Input field re-renders. React.memo only does a shallow comparison of props changes but the handleAddressChange function is recreated new for each render and since functions are compared by reference, React.memo will not able to stop it from re-rendering Input Component as it is prop is callback function, which is new for each render of Parent Component.
The way to optimize this scenario is by using useCallback hook.

Now we have re-rendering only for the components that require it, as callbacks are passed to optimized child components that rely on reference equality to prevent unnecessary renders

š” Now suppose if we have another requirement that is to validate address and show the suggestion. Address Validation API can take some time, lets see that in action
const isValidAddress = () => {
console.log(`validating Address... for ${city}`);
for (let i = 0; i < 10000; i++) {
}
return city.length < 3 ? false : true;
};
This expensive calculation will run on every re-render of Parent component, even when only name field changes. We can optimize this using useMemo hook.

Now the expensive address validation will only run when city value changes.
