반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

undefined

useReducer -React 본문

React

useReducer -React

JavaScripter 2022. 6. 23. 23:38
반응형

1. useReducer란?

 -useState로는 관리하기 힘든 방대한 state를 관리할 수 있다.

 

 

2. 사용이유?

 -효율적인 state의 관리 but 항상 좋은건 아니다. 과할 수 있다.

 -여러개의 state를 하나의 객체 안에서 관리할 수 있다.

 

 

3. 사용 방법

(1). reducer import

import React, { useState, useEffect, useReducer } from 'react';

 

 

 (2). 기본형식

 

const [emailState, dispatchEmail] = useReducer(emailReducer, {
    value: '',
    isValid: null,
  });

 

const [현재 state, 업뎃용 state] = useReducer(함수,{기본값}) // 기본값의 값들은 emailState의 method로 이용됨

 

 

 (3). 함수정의 => 기본 컴포넌트 함수 바깥에서 정의해도 무방 dispatchEmail이 실행되면 useReducer의 함수로 이동하기 때문

 

const emailReducer = (state, action) => {
  return { value: '', isValid: null };
};

 

state는 최신상태, action은 위의 업데이트용 state(dispatchEmail)의 객체

 

return {기본값}

 

 

(4). 값이 바뀔때 state최신화 (dispatchEmail)

 

  const emailChangeHandler = (event) => {
    dispatchEmail({ type: 'userInput', val: event.target.value });
  };

 

dispatchEmail({}) 객체를 넣어줌  (안의 값의 이름은 자유) => action에서 사용될 예정 // action = dispatchEmail안의 객체임

 

 

(5). 현재 state의 값을 필요한 곳에 적용

 

value={emailState.value}

기본값에서 정해준 값을 이용함

 

ex) emailState.value, emailState.isValid

 

 

(6). 리듀서 함수 업데이트

 

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

미리정해둔 값활용

 

이외: emailState를 useEffect의 의존성함수 배열에 추가하여 활용 가능!

 

 

 

4.사용결과

 

이메일의 input이 바뀜 => reducer함수 실행 => 함수 실행 됐을 때 기준의 최신값 로드 => emailState 최신화

 

한번에 많은 state의 최신화 가능

 

 

 

 

반응형

'React' 카테고리의 다른 글

Error Boundary - React  (0) 2022.07.02
UseEffect -React  (0) 2022.06.23
Ref - React  (0) 2022.06.22
Portal -React  (0) 2022.06.22
Comments