How is state being accessed when using a function in setState?

I am trying to figure out how setState can access state without using this? Is it because the method was bound in the constructor? Just like window.document can just be written just as document when accessing it in jQuery?

I understand that state may be used as an argument to make sure it is up to date with the React batch, but I don’t understand its privileges.


class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    visibility: false
  };
  // Change code below this line
  this.toggleVisibility = this.toggleVisibility.bind(this)
  // Change code above this line
}
// Change code below this line
toggleVisibility() {
  this.setState(state => {
    return state.visibility ? {visibility: false} : {visibility: true}
  });
}
// 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 (X11; CrOS x86_64 14150.74.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.114 Safari/537.36

Challenge: Use State to Toggle an Element

Link to the challenge:

Yes, setState is on this and so is state. You bind this into toggleVisibility so it has access to that particular this. Another way would be to use an arrow function for that method.

I understand that state may be used as an argument to make sure it is up to date with the React batch, but I don’t understand its privileges.

I’m not sure what you mean by “privileges”. If you pass setState and object, it merges that with state. If you pass it a function, it will pass in the current state as the first parameter and will merge in whatever you return from your callback function. I’m not sure where “privilege” comes into this.

1 Like