Sobes.tech
Middle

How can data be exchanged between components: from parent to child, from child to parent, between siblings?

sobes.tech AI

Answer from AI

Data exchange between components in the frontend is usually implemented as follows:

  • From parent to child: through passing props (properties). The parent passes data to the child component as parameters.

  • From child to parent: through callback functions passed by the parent to the child component. The child calls this function, passing data back.

  • Between child components: usually through a common parent. One child component calls a callback, the parent updates the state, which is then passed to another child via props. In more complex cases, global state (Redux, Context API) or events are used.

Example in React:

function Parent() {
  const [childData, setChildData] = React.useState(null);

  function handleChildData(data) {
    setChildData(data);
  }

  return (
    <>
      <ChildA onData={handleChildData} />
      <ChildB data={childData} />
    </>
  );
}

function ChildA({ onData }) {
  return <button onClick={() => onData('data from ChildA')}>Send Data</button>;
}

function ChildB({ data }) {
  return <div>Received: {data}</div>;
}
How can data be exchanged between components: from… - sobes.tech