Middle
What happens to the component when the key changes? Explain the lifecycle of functional components.
sobes.tech AI
Answer from AI
When the key of a component in React changes, it causes the old component to unmount and a new one to mount. This is because key is used by React to identify components in lists and optimize rendering.
If the key changes, React considers it a completely different component, so:
- The old component's
componentWillUnmountmethod is called (for class components) or effects are cleaned up (for functional components). - The new component is created anew, and lifecycle methods or effects are invoked.
The lifecycle of functional components in React with hooks:
-
Mounting:
- The component function is executed.
- Effects with
useEffectwithout dependencies or with an empty dependency array are run.
-
Updating:
- The component is re-invoked when props or state change.
- Effects with changed dependencies are executed.
-
Unmounting:
- The cleanup function from
useEffectis executed (if provided).
- The cleanup function from
Example with useEffect:
useEffect(() => {
// effect code
return () => {
// cleanup on unmount or before next effect
};
}, [dependencies]);
Thus, changing the key leads to the complete re-creation of the component, affecting its lifecycle.