본문 바로가기

리액트

prop drilling (프로퍼티 내리꽂기)

The Pure React Way

-> state를 관리할 때 

 

장점: 명시적으로 작성하면 코드를 실행하지 않고도 정적으로 따라가는 것으로 어디서 사용하는지 쉽게 파악할 수 있고 수정도 간단하게 할 수 있다.

 

단점: 누구든 데이터가 어디서 초기화되고 갱신되며 사용되는지 판단하기 쉽지 않은 상황에 마주한다.

  • 일부 데이터의 자료형을 바꾸게 되는 경우 (예: {user: {name: 'Joe West'}}-> {user: {firstName: 'Joe', lastName: 'West'}})
  • 필요보다 많은 프로퍼티를 전달하다가 컴포넌트를 분리하는 과정에서 필요 없는 프로퍼티가 계속 남는 경우
  • 필요보다 적은 프로퍼티를 전달하면서 동시에 defaultProps를 과용한 결과로 필요한 프로퍼티가 전달되지 않은 상황을 문제 인지하기 어려운 경우 (또한 컴포넌트 분리 과정에서도)
  • 프로퍼티의 이름이 중간에서 변경되어서 값을 추적하는데 쉽지 않아지는 경우

단점을 보안하고자 동적 context api를 사용해봤다.

import React, { createContext, useState } from "react";

// Context에서 관리해줄 상태값과 메소드 정의
const CoordinateContext = createContext({
  state: {
    display: "block",
  },
  actions: {
    setDisplay: () => {},
  }
});

// Provider를 rendering하면서 상태값과 메소드들을 전달
const CoordinateProvider = ({ children }) => {
  const [display, setDisplay] = useState(false);

  const value = {
    state: {display},
    actions: {setDisplay}
  };

  return (
    <CoordinateContext.Provider value={value}>
      {children}
    </CoordinateContext.Provider>
  );
};

const CoordinateConsumer = CoordinateContext.Consumer;

export {CoordinateProvider, CoordinateConsumer};

 

context를 가져다 사용할 때 consumer을 사용한다.

<CoordinateConsumer>
  {({actions}) => (
     <Fragment>
       <Coordinate display={actions.setDisplay("none")}/>
     </Fragment>
  )}
</CoordinateConsumer>

 

참고: https://velog.io/@zerozoo-front/context-API-%EC%82%AC%EC%9A%A9%EB%B2%95-3%ED%83%84-%EB%8F%99%EC%A0%81%EC%9C%BC%EB%A1%9C-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

 

context API 사용법 3탄 동적으로 사용하기

대망의 동적인 사용법분석!codesandboxspring-currying-cd7qj?fontsize=14&hidenavigation=1&theme=dark좌클릭은 큰 박스의 색을 변경우클릭은 작은 박스의 색을 변경한다.아래의 두 코드의 상관관계를 이해해보자

velog.io

https://medium.com/@patwa.deepak/still-using-redux-in-2021-clean-your-codebase-using-modern-react-9d4afed45cda

 

Still using redux in 2021? Clean your codebase using Modern React

I developed a very simple blog app using react in 3 different ways.

medium.com

 

'리액트' 카테고리의 다른 글

react & styled-components로 스크롤 꾸미기  (0) 2021.09.28
ref로 HTML Element 접근/제어  (0) 2021.08.10
Invalid Hook Call Warning  (0) 2021.07.28
ReactDOM.render & ReactDOM.createRoot  (0) 2021.07.19
Set up Airbnb Style  (0) 2021.07.05