개발/javascript

[react] hook - 상태관리(useState,useReducer,useContext)

smile-haha 2023. 1. 26. 01:58
반응형

react의 hook은 함수형 컴포넌트에서도 상태관리를 할 수 있게 useState, useEffect 등의 함수를 제공하여 기존의 함수형 컴포넌트에서는 할 수 없었던 다양한 작업을 할 수 있게 해준다.

 

 

내가 사용해본 hook은 useState, useEffect, useContext, useReducer, useMemo, useRef이다.

이번에 복직 준비하면서 다시 api를 보니 여러 hook이 있어 기존의 hook과 함께 공부하고 정리해 보려고 한다.

오늘은 상태를 관리하는 useState, useReducer, useContext 만!

 

1. useState

상태 값과 상태 갱신함수를 반환하는 hook. 초기값은 매개변수로 설정. 

- 배열, object, 숫자, 문자열 등 간단한 데이터를 다룰 때 가볍게 이용하기 좋다

import React, { useState } from 'react';

export default function ReactSample(){

  const [state,setState] = useState({name:'ha',age:31});
  
  return 
    <div>
      {`hi my name is ${state.name} and my age is ${state.age}.`}
      <button type="button" onClick={setState({state...,age:state.age+1})}>increment age</button>
    </div>
}

 

2. useReducer

useState와 같이 상태값을 관리하는 hook. 매개변수로 reducer, 초깃값, 초기화 함수를 받는다.

reducer는 현재 상태 값(state)과 사용자가 넘긴 object(action)를 매개변수로 받는 함수이다.

reducer는 action의 프로퍼티 type에 따라 변경된 상태 값을 조작하여 반환한다.

- 데이터가 복잡한 경우, 또는 변경이 다양하게 많이 이루어지는 경우 이용하기 좋다.

import React, { useReducer } from 'react';

//사람 상태값 관리 리듀서
function PersonReducer(state/*현재 state 값*/, action/*사용자가 넘긴 값*/){
  switch(action.type){
    case 'increment age' : 
      /*이곳에 변경할 상태값을 조작하는 로직을 넣어도 좋다.*/
      return {...state, age : state.age+1};break;
    case 'decrement age' :
      return {...state, age : state.age-1};break;
    case 'rename' :
      return {...state, name : action.name};break;
  }
}
function init(init){
  /** useReducer의 두번째 매개변수로  받은 초기값을 매개변수로 받는 초기화 함수
   *  전달받은 초기값에 뭔가 조작을 해서 초기값으로 사용하고자 할때 
   *  여기에다 작성하면된다.
   */
  return {name:init.name,age:init.age};
}
export default function ReactSample(){

  const [state,dispatch] = useReducer(PersonReducer,{name:'ha',age:31});
  //이렇게도 쓸 수 있다.
  //const [state,dispatch] = useReducer(PersonReducer,{name:'ha',age:31},init);
  
  return 
    <div>
      {`hi my name is ${state.name} and my age is ${state.age}.`}
      <button type="button" onClick={dispatch({type:'increment age'})}>increment age</button>
    </div>
}

 

3. useContext

계층적으로 이루어진 컴포넌트 사이에서 하위 컴포넌트에 데이터를 공유하고 싶을때 사용

/*PersonContext.js*/
import React from 'react';
/*createContext의 매개변수는 context 사용시 값을 지정하지 않았을 경우 사용될 기본 값*/
export defualt const PersonContext = React.createContext({name:'',age:-1});
/*Introduce.js*/
import React, { useContext } from 'react';
import PersonContext from '../context/PersonContext'
import ChildComponent from '../ChildComponent'

export default function Introduce(){
  return 
    <PersonContext.Provider value={{}}>
      <div>
        {`hi my name is ${state.name} and my age is ${state.age}.`}
        <button type="button" onClick={dispatch({type:'increment age'})}>increment age</button>      
        <ChildComponent></ChildComponent>
      </div>
    </PersonContext.Provider>
}
/*ChildComponent.js*/
import React, { useContext } from 'react';
import PersonContext from '../context/PersonContext'

export default function ChildComponent(){
  const personContext = useContext(PersonContext);
  return 
  <div>{`하하 여기는 자식 컴포넌트! 여기서 상위 컴포넌트에서 보낸 context 받아 볼 수 있지!`
        +`${personContext.age}살 ${personContext.name}`}
  </div>
}

 

반응형

'개발 > javascript' 카테고리의 다른 글

[npm] webpack에서 babel 설정  (0) 2023.01.20
[javacript] ES6 Map/Set  (0) 2023.01.04
[javascript] ES6 배열 함수  (2) 2023.01.02
[javascript] 원시타입과 객체 Boolean으로 변환  (0) 2023.01.01
ECMAScript 2015(ES6)  (0) 2022.12.30