Ir para o conteúdo

QuizNão tentada

Inicialização lazy do useReducer

Clicando no botão 3 vezes, quantas vezes no total 'lazy init' é logado?
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 escolher, Enter para enviar
Ver resposta e explicação

Resposta correta:

  • 1
  • O terceiro argumento init é chamado uma vez na montagem como init(start)
  • dispatches e re-renders posteriores reaproveitam o state armazenado, então loga uma vez.
  • Não 3 ou 4: init não é chamado a cada render nem a cada dispatch.
  • Não 0: ele precisa rodar para produzir o state inicial.