React Context는 오랫동안 사용이 가능했지만 이번에 React hooks이 나오면서 더 좋아졌다. 이전에는 redux라는 third-party libraries를 사용해서 React Apps의 상태를 관리했었다. 이 개발자가 redux에 대한 내용 을 작성했는데, redux를 사용할 개발자들은 이 해당 포스트를 참고해도 좋을것 같다. (참고로 이 코드를 React context hook 으로 리팩토링을 진행했음

React Redux를 사용할때

나는 react-context-hook을 사용하고 싶으니... 이 코드의 흐름을 이해해보려고 한다. 이전 redux를 사용할때는 component, container, ilb/api, modules를 각각 생성했었는데, 코드 관리가 어려웠다. 하나의 API를 추가하려면 너무 많은 작업이 필요했고, 여러 파일을 변경하면서 수정하는게 보통 쉬운게 아니다. 내가 모듈에 작성했던건지.. lib/api에 작성했던건지 나도 기억이 안나니.. 보통 Redux를 사용하면 Component에 내가 원하는 UI를 표시하고, Container안에 component를 넣고 container에서는 데이터를 lib/api, modules을 통해 가져온다. 역할로 나눠보면 lib/api, modules은 데이터 처리를 해주고, container에서는 데이터 처리의 상태를 확인하다가 변경된 부분이 있다면 데이터를 업데이트를하고, component에서는 container에서 업데이트된 데이터를 화면에 출력을 한다.

위 작업을 하기 위해서는 첫번째로 component를 작성하고, 두번째로 lib/api, module을 작성을 한뒤에 컴포넌트에 데이터가 정상적으로 들어가는지 확인하고, 이후에는 변경되는 데이터를 확인하고 업데이트하는 container를 작성해 최종적으로 component가 아닌 container를 pages에 추가했었다. 이방법이 정답은 아니겠지만 내가 본 책에서는 그랬다. 지금 다른 코드를 보면 이 책도 예전 방식을 따라했던것 같다. 너무 빠르게 변화함..

React Context를 사용하면

React Context를 사용하면 context, container, component를 생성하면된다.

  • Context
    • reducer를 구현해 어떤 액션 타입이 왔을때 어떻게 데이터를 리턴할지에 대해서 명시
    • 추가로 article에 대한 articleContext.js를 생성하고, 그 안에는 ArticleProvider를 정의한다. 이 Provider는 값을 전달하는 역할을 한다.
  • Container
    • container는 context를 이용해 article의 내용을 가져오는 역할을 한다. useContext(ArticleContext를 통해 articles을 가져오고 article을 화면에 출력할 내용을 생성한다. (출력할때 component에 미리 Article 을 만들어놓으면 여기서 사용)
  • Component
    • 위 container에서 작업할 Article을 만든다.
    • ArticleAdd.js를 생성하는데 여기서도 useContext(ArticleContext)을 이용해 dispatch를 가져온다.
      • newAddArticle과 같은 함수를 호출한다.
      • 호출되는 함수에서는 dispatch를 통해 새로운 Article이 추가되었다고 알린다.
  • App.js
    • 최종 앱에는 아래 같은 하위 구성을 정의한다.
      • ArticleProvider (context)
        • AddArticle (component)
        • Articles (container)

참고

서브 라우트는 라우트 내부에 라우트를 다시 정의 하는 것을 의미한다. 사용하는 경우에는 App에서 라우팅을 여러군대로 한다면 코드는 App에서 정말 복잡한 결과를 낼것이다. 우리는 여러개의 컴포넌트를 만들고 연관되는 컴포넌트끼리 내부에서 다시 라우터를 정의해 App에서의 다양하고 복잡한 routing을 효과적으로 정리가 가능하다.

예를들어서 Location에 관련된 컴포넌트에서 Location은 Seoul, Gyonggi-do, (...) 가 있을때 App에 모든 도시의 리스트를 정의하기에는 복잡하다. Location Routing Example 에서 App에 seoul, gyonngi-do를 정의 했는데 Locations라는 라우트 컴포넌트를 따로 정의하고, Location 컴포넌트를 서브 라우트로 사용해보자

코드

import React from 'react';
import { Route, Link } from 'react-router-dom';
import './App.css';

import Home from './components/Home';
import Search from './components/Search';
import Locations from './components/Locations';

const App = () => {
  return (
    <div>
      <Link to="/">홈</Link>
      <Link to="/search">검색</Link>
      <Link to="/locations">위치</Link>

      <Route path="/" component={Home} exact={true}></Route>
      <Route path="/search" component={Search}></Route>
      <Route path="/locations" component={Locations}></Route>
    </div>
  );
};

export default App;
import React from 'react';
import { Link, Route } from 'react-router-dom';
import Location from './Location';

const Locations = () => {
  return (
    <div>
      <h1> 도시 목록 </h1>
      <ul>
        <li>
          <Link to="/locations/seoul">서울</Link>
        </li>
        <li>
          <Link to="/locations/gyonggi">경기</Link>
        </li>
      </ul>
      <Route
        path="/locations"
        exact={true}
        render={() => <div> 지역을 선택해 주세요. </div>}
      />
      <Route path="/locations/:cityname" component={Location} />
    </div>
  );
};

export default Locations;

UI개발할때 항상 내부의 기능과 연결이 되어있으면 코드의 유지보수가 어려운데 storybook을 사용하면 isolation이 되서 UI만 따로 구성할 수 있는 장점이 있다. UI컴포넌트들을 생성하고, 그 컴포넌트들을 사용하면 끝! 

동작하는 방식은 yarn으로 설치를 하고 나만의 stroybook을 로컬에 띄우고 UI를 컴포넌트 별로 생성하고 관리하면 된다. 스토리북을 처음에 동작시키면 아래와 같이 브라우저에 표시가 되는데

ㅋㅋ

내가 만약 UI 컴포넌트 별로 여러개의 UI를 만든다면 아래와 같이 구성이 된다. story에는 내가 작성한 코드들이 들어있고, 버튼을 누를때 action이 있다면 actions에 표시가 된다. 

https://storybook.js.org/docs/basics/introduction/

 

https://storybook.js.org/docs/basics/introduction/

Introduction Edit this page Storybook is a user interface development environment and playground for UI components. The tool enables developers to create components independently and showcase components interactively in an isolated development environment.

storybook.js.org

스토리북에 대해서 학습하고 싶으면 아래 튜토리얼을 따라해보자.

https://www.learnstorybook.com/

 

Storybook Tutorials

Learn Storybook teaches frontend developers how to create UIs with components and design systems. Our free in-depth guides are created by Storybook maintainers and peer-reviewed by the open source community.

www.learnstorybook.com

Airbnb에서도 다음과 같이 자신만의 stroybook을 만들어서 운영하고 있다. 

https://airbnb.io/react-dates/?path=/story/drp-calendar-props--open-up

 

Storybook

 

airbnb.io

이렇게 UI 컴포넌트 별로 생성해서 프로젝트에서의 의존성을 줄이는게 좋을것 같다는 생각!

+ Recent posts