본문 바로가기
Study Note/React

React #Understanding useReducer()

by 시뮝 2022. 9. 24.
728x90

useReducer()

const [state, dispatchFn] = useReducer(reducerFn, initialState, initFn);

 

  • state: The state snapshot used in the component re-render/ re-evaluation cycle
  • dispatchFn: A function that can be used to dispatch a new action (i.e. trigger an update of the state)
  • reducerFn: (prevState, action) => new State / A function that is triggered automatically once an action is dispatched (via dispatchFn()) - it receives the latest state snapshot and should return the new, updatedd state.
  • initialState: The initial state
  • initFn: A function to set the inital state programmatically.

 

Sample code

import { useState } from 'react';

const emailReducer = (state, action) => {
  if (action.type === 'USER_INPUT') {
    return { value: action.val, isValid: acion.val.includes('@') };
  }
  if (action.type === 'INPUT_BLUR') {
    return { value: state.value, isValid: state.value.includes('@') };
  }
  return { value: '', isValid: false }
};

const Login = (props) => {
  const [emailState, dispatchEmail] = useReducer(emailReducer, {
    value: '',
    isValid: null,
  });
  
  const emailChangeHandler = (event) => {
    dispatchEmail({ type: 'USER_INPUPT', val: event.target.value });
    
    setFormIsValid(
      event.target.value.includes('@') && enteredPassword.trim().length > 6
    );
  }
  
  const validateEmailHandler = (event) => {
    dispatchEmail({ type: 'INPUT_BLUR' });
    
    setFormIsValid(
      event.target.value.includes('@') && enteredPassword.trim().length > 6
    );
  }
  
  //...
};

export default Login;

 

useState() vs useReducer()

  • useState()
    • The main state management "tool"
    • Great for independent pices of state/ data
    • Great if state updates are easy and limited to a few kinds of updates
  • useReducer()
    • Great if you need "more power"
    • Should be considered if you have related pieces of state/ data
    • Can be helpful if you have more complex state updates

 

 

728x90

댓글