React 16.3 새 Context API로 Props Drilling 해결하기
문제 상황
사내 대시보드 프로젝트에서 테마 색상과 언어 설정을 여러 depth의 컴포넌트에서 사용해야 했다. Redux를 쓰기엔 과한 감이 있었고, props를 5~6단계 내려주는 것도 비효율적이었다.
새 Context API
React 16.3에서 정식 Context API가 추가되었다. 기존의 실험적 API와 달리 안정적으로 사용할 수 있다는 공식 발표가 있었다.
// ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext({
theme: 'light',
toggleTheme: () => {}
});
export default ThemeContext;
// App.js
class App extends React.Component {
state = {
theme: 'light'
};
toggleTheme = () => {
this.setState(prev => ({
theme: prev.theme === 'light' ? 'dark' : 'light'
}));
};
render() {
return (
<ThemeContext.Provider value={{
theme: this.state.theme,
toggleTheme: this.toggleTheme
}}>
<Layout />
</ThemeContext.Provider>
);
}
}
// ThemedButton.js
const ThemedButton = () => (
<ThemeContext.Consumer>
{({ theme, toggleTheme }) => (
<button
style={{ background: theme === 'light' ? '#fff' : '#333' }}
onClick={toggleTheme}
>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
적용 결과
- props drilling 5단계 제거
- 코드 가독성 향상
- Redux는 복잡한 비즈니스 로직에만 사용
간단한 전역 상태는 Context로 충분했다. 다만 Provider 중첩이 많아지면 코드가 지저분해지는 문제가 있어서, 필요한 경우에만 제한적으로 사용하기로 했다.