reactjs / reactjs/react.dev

[Hooks] - callbacks in useState hook examples

Aberta
#1,480 3 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Linguagem predominante
JavaScript
Estrelas
11.8k
Forks
7.9k
Merge médio
1d 11h
PRs com merge (30d)
11

Descrição

I would like to discuss about using callbacks to create new state which bases on current state in documentation for useState hook.
Current examples can be confusing for new developers which are not very familiar with js.
It would be easier for new developers to learn the rule like newer use value from this.state (for setState) or take current state value from scope (for hooks) to create new state. This simple rule leads to smaller amount of bugs.

So new developers can take this example from https://reactjs.org/docs/hooks-intro.html

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

and convert to something like this:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

with assumption that it will increment by 2 but it does not (it's based on observation with junior developers).

Shouldn't we change first example (and all 'counter' based examples in docs) to something like this?

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(currentValue => currentValue + 1)}>
        Click me
      </button>
    </div>
  );
}

and create new example to show 'standard' way to set state (example where new state is not based on current one).
Or maybe we should just say it's how JS (closures) works and left examples as is?
What's your opinion? I can create PR with changes but I'm not sure which path to choose. On the one hand it's how JS works but on the other hand I see it's confusing.

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece com o exemplo de useState em https://reactjs.org/docs/hooks-intro.html e revise os outros exemplos baseados em contadores na documentação. Este issue precisa de uma decisão de um maintainer entre alterar os exemplos e explicar o comportamento existente; ele estará concluído quando a orientação escolhida estiver documentada de forma consistente.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
javascript, react
Domínio
documentation
Tipo de issue
Documentação
Dificuldade
5/5
Tempo estimado
Mais de uma semana
Status de atividade
Estagnada
Clareza
Precisa de esclarecimento
Facilidade para iniciantes
32/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.