1

useReducer Hook [EN][ES]

UseReducer -click me for official info-

An alternative to useState when the state logic of a component gets complex. For example sub-values or states that depend on previous ones.

This Hook returns a dispatch method, it’s the reducer it means it contains the function logic to update the state; the state is the current state or states of the component; init, it’s optional as the third argument and is a function that allows you to initialize the state. Here an example:

const initialState = {count: 0};

functionreducer(state, action) {
  switch (action.type) {
    case'increment':
      return {count: state.count + 1};
    case'decrement':
      return {count: state.count - 1};
    default:
      thrownewError();
  }
}

functionCounter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <buttononClick={() => dispatch({type: 'decrement'})}>-</button><buttononClick={() => dispatch({type: 'increment'})}>+</button></>
  );
}
<h3>Lazy initialization</h3>

There two ways to initialize the state of the component, one is directly setting the values or we can use a lazy function, the init function in the useRender argument.

The third argument is independent of the reducer, what it means we can employ to reset the state if we want so.

<h3>Bailing out</h3>

One difference from useEffect that Rect won’t re-render if the reducer returns the same value as the previous one. But if you need to calculate complex operation before render, React recommends the use of the hook useMemo.
[ES]

UseReducer -haga clic en mí para obtener información oficial-

Una alternativa a ** useState ** cuando la lógica de estado de un componente se vuelve compleja. Por ejemplo subvalores o estados que dependen de los anteriores.

Este Hook devuelve un método de despacho, es ** el reductor ** significa que contiene la lógica de la función para actualizar el estado; ** el estado ** es el estado o estados actuales del componente; ** init **, es opcional como tercer argumento y es una función que le permite inicializar el estado. Aquí un ejemplo:

`` jsx
const initialState = {count: 0};

reductor de función (estado, acción) {
switch (action.type) {
caso ‘incremento’:
return {count: state.count + 1};
caso ‘decremento’:
return {count: state.count - 1};
defecto:
lanzar nuevo Error ();
}
}

función Contador () {
const [estado, envío] = useReducer (reductor, estado inicial);
regreso (
<>
Recuento: {state.count}
<button onClick = {() => despacho ({type: ‘decrement’})}> - </button>
<button onClick = {() => despacho ({tipo: ‘incremento’})}> + </button>
</>
);
}
’’

<h3>Inicialización perezosa</h3>

Hay dos formas de inicializar el estado del componente, una es establecer directamente los valores o podemos usar una función lazy, la función init en el argumento useRender.

El tercer argumento es independiente del reductor, lo que significa que podemos emplear para restablecer el estado si así lo queremos.

<h3>Rescate</h3>

Una diferencia con ** useEffect ** es que Rect no volverá a renderizar si el reductor devuelve el mismo valor que el anterior. Pero si necesita calcular una operación compleja antes de renderizar, React recomienda el uso del gancho useMemo.

Escribe tu comentario
+ 2