Saltar al contenido

TestSin intentar

Inicialización perezosa de useReducer

Al pulsar el botón 3 veces, ¿cuántas veces en total se imprime 'lazy init'?
function init(initialCount) {
console.log('lazy init');
return { count: initialCount };
}
function reducer(state, action) {
return action.type === 'inc' ? { count: state.count + 1 } : state;
}
function App({ start }) {
const [state, dispatch] = useReducer(reducer, start, init);
return <button onClick={() => dispatch({ type: 'inc' })}>{state.count}</button>;
}
1–4 para elegir, Enter para enviar
Ver respuesta y explicación

Respuesta correcta:

  • 1
  • El tercer argumento init se llama una vez al montar como init(start)
  • los dispatch y re-renders posteriores reutilizan el estado guardado, así que se imprime una vez.
  • No 3 ni 4: init no se llama en cada render ni en cada dispatch.
  • No 0: debe ejecutarse para producir el estado inicial.