Calculation in child components that reflect(Recursively) in parent component

Viewed 214

Suppose i have main Parent Component A. Which has two children B and C components And C component itself a Parent component which also has two children means D and E.

graph of objects

So, If i change calculation in E component that should be instant update in that immediate parent C as well as update in parent A.

So what should be the recursive way that should full fill my requirement.

1 Answers

You're in luck - React was built to solve this problem (among other things). There are two ways React takes care of this for you: Props and State. Props are data passed down from one component to another; they are immutable. State is like an in-memory cache for individual components, and can be passed down to child components as Props. React "reacts" to reassignment of those immutable properties. Any reassignment will cause an updated re-render of your components.

There are two main solutions - the classical React way, and through shared state. The classical React way would be to store the data, and the calculation, in a parent component, and pass a callback down to a child component that would perform the calculation. I.e.:

class A extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      number: 0,
    };
  }

  setNumber(number) {
    this.setState({ number });
  }

  render() {
    <A />
    <B number={number} setNumber={this.setNumber} />
  }
}

class B extends React.Component {
  constructor(props) {
    super(props);
    const { number, setNumber } = props;
  }

  render() {
    {number}
    <button onClick={() => setNumber(number + 1) />
  }
}

This works fine but is not very scaleable. In the structure you provided, you'd have to pass down number and setNumber down a tree of children (sometimes called "prop drilling"). Imagine restructuring a large tree of these children and you can see why this is not a very popular solution.

So, this usually gets solved by creating a shared state that all components can access. React Context can be used for this, and there are also many third-party libraries to this end. Redux is probably the best-known. The goal of all of them is roughly the same - provide a large object of common state that any component can pull from, regardless of its location in the tree. Redux's selectors (for example) are built on the same immutability principle, where reassignment will cause a re-render just as though it was a prop from a parent component.

Some recommended reading:

Related