reactjs / reactjs/react.dev

Confusing setState() documentation

Ouverte
#715 8 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Langage dominant
JavaScript
Étoiles
11.8k
Forks
7.9k
Merge moyen
1 j 11 h
PR mergées (30 j)
11

Description

I have a general question about setState() because the documentation about this is a little bit confusing:

I have a component with a state. This state should only be updated (re-rendered) when a condition met. If not then there is no need to re-render the component. Reading the docs about setState tells me that reading this.state right after calling setState() is a potential pitfall. Instead I should use setState with an updater function because there prevState is guaranteed to has the right value. So my first approach was:

class MyComponent extends React.Component {
  onSomething = () => {
    this.setState(prevState => {
      if (prevState.counter < 10) {
        return { counter: prevState.counter + 1 };
      }
      return prevState;
    });
  }
}

But with that approach my component always get re-rendered because setState() always forces a re-render (in the beginning I thought that when I return the same prevState object React does nothing. But I was wrong). So what else can I do to avoid re-rendering?

Again in the same doc we can read that calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders. So I could re-write my code into following:

class MyComponent extends React.Component {
  onSomething = () => {
    if (this.state.counter < 10) {
      this.setState(prevState => {
        return { counter: prevState.counter + 1 };
      });
    }
  }
}

But then if (this.state.counter < 10) could have a different value than prevState.counter

So on the one side the docs recommend to not read from this.state directly because the calls to setState() could be batched and this.state has an outdated value but on the other side it recommends to call setState() only when the new state differs from the old state. But how can I check if the state differs when it could be potentially outdated?

In the end I don't know actually how to set my state and avoid a re-rerender when a condition met. Any help here would be great.

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez par la documentation liée de setState() et les exemples de cet issue, puis vérifiez comment sont décrites les fonctions updater, le batching et le nouveau rendu. Le travail est terminé lorsque la documentation résout clairement la contradiction apparente et explique comment éviter un nouveau rendu inutile lorsque la condition est remplie.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
javascript, react
Domaine
documentation
Type d'issue
Documentation
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
À clarifier
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.