0
class Counter extends Component {
constructor(props) {
    super(props);
    this.state = {
        age: 10,
    };
}
handleincrement = () => {
    console.log("hy");
    this.setState((prevState) => {
        return { age: prevState.age + 1 };
    });
}
render() {
    return (
        <div>
            <button onClick={this.handleincrement}>
                counter value is {this.state.age}
            </button>
        </div>
    );
}

}

function App() {
return (
    <div>
        <Counter />
        <Counter />
    </div>
);

}

I have a one component Counter and i am using is 2 time times in App.js class when i click first button it result in increasing state value of only first Counter component and vice verse. My question is that why these both components behave independentaly from each other?

  • because the counter component has its own state. Two Counter Child component means they both have their independent instance as well as states. – bakar_dev Jul 08 '20 at 07:37

2 Answers2

1

Each component has its own lifecycle.

For sharing the same state, what is recommended, is lifting the state up:

class Counter extends React.Component {
  render() {
    return <div>{this.props.age}</div>;
  }
}

class App extends React.Component {
  state = {
    age: 0
  };

  handleincrement = () => {
    this.setState(prev => ({ age: prev.age + 1 }));
  };
  render() {
    return (
      <div>
        <button onClick={this.handleincrement}>Increase</button>
        <Counter age={this.state.age} />
        <Counter age={this.state.age} />
      </div>
    );
  }
}

For completeness, you can use a global variable too (not recommended).

Something like:

let age = 10;

class Counter extends React.Component {
  handleincrement = () => {
    age++;
    this.forceUpdate();
  };
  render() {
    return (
      <div>
        <button onClick={this.handleincrement}>counter value is {age}</button>
      </div>
    );
  }
}
const App = () => {
  return (
    <div>
      <Counter />
      <Counter />
    </div>
  );
};

Edit Q-62789676-LiftStateUp

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

It is because both are separate Child Components of Parent class App. This not a constructor props or something that is within App Class. You are importing both components so they are just coming individually.

Hamza Mughal
  • 504
  • 4
  • 10