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>
'리액트' 카테고리의 다른 글
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 |