[Solved] Why doesn’t React automatically allow child components to call setState of the parent component?


React, and the Flux pattern (that helps manage complex application with multiple React components) espouse uni-directional data flow. Uni-directional data flow makes an application easy to reason, and debug because:

  • If there is something wrong with a React component, you trace upwards to the parent recursively until you find the root cause, because the data flow/setState could have only come upstream

Child React components do indirectly setState of parent but only through notifying parents about certain events, e.g., a mouse click. The parent itself then decides if the mouse click should trigger setState of its own state, which is passed down as props to its children.

class ParentComponent extends React.Component {
  onClick() {
    const _childValue = this.state.childValue; 
    this.setState({ childValue: _childValue + 1 });
  } 
  render() {
    return (<ChildComponent value={this.state.childVvalue} onClick={this.onClick.bind(this)} />)
  } 
} 
class ChildComponent extends React.Component {
  render() {
    return (
      <span> 
        <div>My value: {this.props.value} </div>
        <button onClick={this.props.onClick}>Increment</button> 
      </span> 
    ) 
  } 
} 

1

solved Why doesn’t React automatically allow child components to call setState of the parent component?