Blog>
Snippets

Prop-Driven State Initialization in Child Components

Detail the process of initializing state in a child component using values received from props.
class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    // Initialize the state with a prop value
    this.state = {
      initialValue: props.value
    };
  }

  render() {
    // Render the component based on the state initialized with props
    return <div>{this.state.initialValue}</div>;
  }
}
This is a class component in React that is using its props to initialize its state in the constructor. The value passed via props is being set as the initialValue of the state.
const ChildComponent = (props) => {
  // Use the useState hook to initialize the state with a prop value
  const [initialValue, setInitialValue] = React.useState(props.value);

  return <div>{initialValue}</div>;
};
This is a functional component in React using the useState hook to initialize its state with a value received from props. The state is then used to display the initial value.
class ChildWithDerivedState extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Update the state only when the prop has changed
    if (nextProps.value !== prevState.value) {
      return { value: nextProps.value };
    }
    // Return null to indicate no change to state
    return null;
  }

  constructor(props) {
    super(props);
    this.state = { value: props.value };
  }

  render() {
    return <div>{this.state.value}</div>;
  }
}
This class component demonstrates the use of getDerivedStateFromProps to update the state whenever the prop value changes. The state is initialized with the prop value in the constructor and re-initialized if the prop changes after the initial mount.