Today I Learned - Rocky Kev

TIL React - SetState

POSTED ON:

TAGS:

props get passed to the component (similar to function parameters).
state is managed within the component (similar to variables declared within a function).

more info

Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).


//won't work
incrementCount() {
  this.setState({count: this.state.count + 1});
}

//will work
incrementCount() {
  this.setState((state) => {
    // Important: read `state` instead of `this.state` when updating.
    return {count: state.count + 1}
  });
}

handleSomething() {
  // Let's say `this.state.count` starts at 0.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();
}


Related TILs

Tagged:

TIL How to implement two-way binding without a framework

One of the reasons we use React or Vue is because of that sweet sweet two-way binding. It's the automatic syncing of data between the model (data) and the view (UI) in both directions. Any changes made to the data will automatically update the view, and any changes made to the view will automatically update the data.

TIL how Svelte is different fom Vue/React

TIL about Concurrency

It means tasks can overlap.