skip to Main Content

The setState method is used to update a single state variable at a time. Is this statement True or False. If true, why?

I’m confusing about that statement. It can also update a single state variable also or only it can update multiples values.

please clarify me about that statement

2

Answers


  1. The setState can update the entire state of the component. Let’s say you have a component:

    class App extends Component { 
      constructor(props){ 
        super(props) 
            
        // Set initial state 
        this.state = {
          name: "Nil",
          age: "0",
          score: "0"
        } 
      }
          
      render(){ 
        return ( 
          //... 
        ) 
      } 
    }
    

    Using the setState method you can update 1,2 or all 3 state variables by calling it:

        this.setState({
          name: 'Bob',
          age: '18',
          score: '30'
        }) 
    

    So yes the setState accepts only 1 input argument, but that input argument is the object representing the entire state of the component

    Login or Signup to reply.
  2. It is true, but then your variable could be a list or an object, and contain "inner-variables" if that makes sense.

    Also you can call setState multiple time, it’s just the way to hook events in modern web clients.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search