Components receive data through props, which are passed from parent to child components. When a parent component's state or props change, it triggers a re-render of its child components, ensuring they receive the updated props.
Class Components:
In class-based components, you can respond to prop changes using lifecycle methods:
componentDidUpdate(prevProps): This method is invoked immediately after updating occurs. You can compare prevProps with the current this.props to detect changes and perform necessary actions.
class MyComponent extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.data !== this.props.data) {
// Perform actions in response to prop change
}
}
render() {
// Render component
}
}
Functional Components:
With functional components, the useEffect hook serves a similar purpose:
useEffect with Dependency Array: By specifying props in the dependency array, the effect runs whenever those props change.
import React, { useEffect } from 'react';
const MyComponent = ({ data }) => {
useEffect(() => {
// Perform actions in response to prop change
}, [data]);
return (
// Render component
);
};