Sobes.tech
Junior — Middle

How is data transferred between components in React?

sobes.tech AI

Answer from AI

In React, data transfer between components is mainly done through props and state.

  • Props are properties that the parent component passes to the child. They are read-only in the child component.
  • State is the internal state of the component, which can be changed within the component itself.

To pass data from parent to child, props are used:

function Parent() {
  const message = "Hello from parent!";
  return <Child text={message} />;
}

function Child(props) {
  return <div>{props.text}</div>;
}

For passing data between unrelated components, React Context or global state (e.g., Redux) are often used.

You can also pass functions via props so that the child component can call parent methods and thus change state or pass data back.