reactjs / reactjs/react.dev

A note about not firing side effects in useState(prev => next) ?

Abierto
#2,882 2 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

So I ended up doing this by mistake after a wonky merge:

let Foo = (props) => {
    let [bar, setBar] = useState();
    
    let handleClick = () => {
        useState(bar => {
            let newBar = bar + 1;
            props.handleBarChange(newBar); // bad, which isn't surprising
            return newBar;
        });
    };

    return <div onClick={handleClick}>click me</div>;
};

If you fire a side effect such as calling something that sets state in a higher component from a useState updater function, you get the error "Cannot update a component from inside the function body of a different component" (but not always! It seems to depend on internal timing). This definitely seems like a bad idea when you look at it, but I couldn't find any mention in the docs that this is bad.

https://reactjs.org/docs/hooks-reference.html#functional-updates

There is the note about side effects generally on useEffect:

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase)

But this is not in the main body of a function component, doesn't feel like a true side effect as it's still just setting state within React, and doesn't feel like it's in the render phase either.

I initially wanted to comment about this here (https://github.com/facebook/react/issues/18178), because the general message of that thread was "don't set state of another component in a render method", and I've managed to get this error message without doing that, but the thread is locked. Thanks.

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 la página de referencia de Hooks enlazada, especialmente con la sección sobre actualizaciones funcionales, y compara sus indicaciones con la nota citada sobre efectos secundarios de useEffect. Aclara si los efectos secundarios dentro de un actualizador de useState no son compatibles y explica el comportamiento relevante; se considerará terminado cuando la documentación aborde este ejemplo sin ambigüedad.

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
2/5
Tiempo estimado
1-3 horas
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.