React - Use State to Toggle an Element

Tell us what’s happening:
Describe your issue in detail here.

I am confused with the concept freecodecamp trying to explain here. Can any one explain me in better way please?

  **Your code so far**
class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    visibility: false
  };
  // Change code below this line

  // Change code above this line
}
// Change code below this line

// Change code above this line
render() {
  if (this.state.visibility) {
    return (
      <div>
        <button onClick={this.toggleVisibility}>Click Me</button>
        <h1>Now you see me!</h1>
      </div>
    );
  } else {
    return (
      <div>
        <button onClick={this.toggleVisibility}>Click Me</button>
      </div>
    );
  }
}
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Linux; Android 10; Redmi Note 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Mobile Safari/537.36

Challenge: React - Use State to Toggle an Element

Link to the challenge:

Hey! Are you having trouble understanding the concept of “State” or do you just want to ask how the code snippet you mentioned is working.

No I understood what is state, but for this particular problem I am not getting, what is going on

What we are doing here?

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

why here we are using counter and increment and +

State consists of all of the dynamic data in your component. Whenever the value of state changes the entire react component and all of its children need to rerender.

As for this example, when your state update relies on a previous value of state, for example if you have a counter and you want to add one to it each time a button is clicked, instead of using the state directly, you need to pass a callback function to the setState function. The function that you pass to the setState function will get the previous snapshot of state and props automatically and you can use them to make further updates. this is just an example that demonstrates it.

Passing a callback function to the setState function is really important when you wanna make sure that you have the most updated value of the previous state. if you want to read more about it, here’s an article that can help you understand it clearly.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.