Sobes.tech
Middle+

Can we change props in a child component?

sobes.tech AI

Answer from AI

In a child component, you cannot directly change props because props are input data passed from the parent to the child and are considered immutable within the child component.

If you need to change data passed through props, usually:

  • The parent should pass a callback function in the props, which the child component calls to change the parent's state.
  • Or use local state in the child component if the data should not be synchronized with the parent.

Example in React:

function Parent() {
  const [value, setValue] = React.useState(0);
  return <Child value={value} onChange={setValue} />;
}

function Child({ value, onChange }) {
  return <button onClick={() => onChange(value + 1)}>Increment</button>;
}

Thus, the child component does not change props directly but initiates a change through a callback.