reactjs / reactjs/react.dev

[Hooks] - callbacks in useState hook examples

Abierto
#1,480 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
JavaScript
Estrellas
11.8k
Forks
7.9k
Merge medio
1 d 11 h
PR fusionados (30 d)
11

Descripción

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.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con el ejemplo de useState en https://reactjs.org/docs/hooks-intro.html y revisa los demás ejemplos basados en contadores de la documentación. Este issue necesita que un maintainer decida entre cambiar los ejemplos y explicar el comportamiento existente; se considerará terminado cuando la orientación elegida esté documentada de forma coherente.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
javascript, react
Área
documentation
Tipo de issue
Documentación
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
32/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.