<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 이소영 on Medium]]></title>
        <description><![CDATA[Stories by 이소영 on Medium]]></description>
        <link>https://medium.com/@soyoung.dev?source=rss-42da4571cdf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NX9JU4hoZz8goUKvsgK97w.jpeg</url>
            <title>Stories by 이소영 on Medium</title>
            <link>https://medium.com/@soyoung.dev?source=rss-42da4571cdf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:26:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@soyoung.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hooks 이해하기: useState, useEffect]]></title>
            <link>https://medium.com/humanscape-tech/hooks-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-usestate-useeffect-811636d1035e?source=rss-42da4571cdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/811636d1035e</guid>
            <dc:creator><![CDATA[이소영]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 05:51:50 GMT</pubDate>
            <atom:updated>2019-08-30T02:12:53.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Hooks는 <a href="https://www.youtube.com/watch?v=dpw9EHDh2bM"><em>React v16.8</em></a>에 새롭게 도입된 기능입니다. 그 동안 어떤 기능인지 살펴보는 것을 미루고 있었는데, 근래의 create-react-app이나 많은 보일러 플레이트에서 함수형 컴포넌트를 기본으로 하는 것을 보고 <em>‘이제는 공부해야겠다.’</em>는 생각이 들어서 정리하게 되었습니다.</p><h3>Before Hooks..</h3><p>Hooks는 함수형 컴포넌트에 state를 제공함으로써 상태 관련 로직의 재사용을 이전보다 훨씬 쉽게 만들어줍니다. 그렇다면 Hooks가 나타나기 전, 우리는 <strong>상태 관련 로직을 어떻게 재사용</strong> 했을까요?</p><p>React의 가장 기본이 되는 단위는 컴포넌트 입니다. 그래서 우리는 공통된 로직을 분리해 하나의 클래스 컴포넌트로 만들어 재활용했습니다. React에 대해 어느 정도 익숙해지고 나면 듣게 되는 HOC(Higher-Order Component) 패턴이 예시입니다.</p><h4>HOC(Higher-Order Component)</h4><p>HOC는 input으로 컴포넌트를 받아 필요한 로직을 추가한 후 output으로 추가된 컴포넌트를 반환합니다. 많은 React 프로젝트에서 사용하고 있는 Redux가 HOC 패턴으로 구현되었습니다.</p><pre><em>import</em> { Enhance } <em>from</em> &quot;./Enhance&quot;;<br><br>class MyComponent {<br>  render() {<br>    if (!<em>this</em>.data) <br>      return &lt;div&gt;Waiting...&lt;/div&gt;;<br>    <br>    return &lt;div&gt;{<em>this</em>.data}&lt;/div&gt;;<br>  }<br>}<br><br><em>export</em> default Enhance(MyComponent); // Enhanced component</pre><p>로직이 담긴 Enhance 컴포넌트로 MyComponent를 감싸서 공통된 로직을 MyComponent나 또 다른 컴포넌트로 전달할 수 있습니다.</p><p><em>HOC나 함수형, 클래스형 컴포넌트에 대한 더 자세한 설명은 </em><a href="https://medium.com/little-big-programming/react%EC%9D%98-%EA%B8%B0%EB%B3%B8-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8%EB%A5%BC-%EC%95%8C%EC%95%84%EB%B3%B4%EC%9E%90-92c923011818"><em>이 글</em></a><em>을 참고해주세요.</em></p><h4>Render Props</h4><p>또 다른 방법으로는 Render Props 패턴이 있습니다. React Router 라이브러리가 이 패턴을 따라 구현되었습니다.</p><p>Render Props 패턴으로 구현된 컴포넌트는 자체적으로 rendering 로직을 구현하는 대신 React element 요소를 반환하고, 이를 호출하는 함수를 사용합니다. Render Props 패턴을 구현한 코드는 <a href="https://medium.com/@la.place/react-render-props-pattern-1c53a6b9645c">여기</a>에서 확인할 수 있습니다.</p><p><em>Render Props 패턴에 대한 더 자세한 설명은 </em><a href="https://reactjs.org/docs/render-props.html"><em>이 글</em></a><em>을 참고해주세요.</em></p><p>재사용 되는 로직을 함수로 분리한다는 것은 당연하게 느껴집니다. 하지만 지금까지 React에서 함수는 local state를 가질 수 없었습니다. 그래서 state와 관련된 로직을 분리하기 위해서는 클래스 컴포넌트를 만들고, 위에서 본 것과 같은 복잡한 패턴을 사용해왔습니다.</p><p>로직의 재사용을 위해서 Component Tree에 또 하나의 depth가 추가되어야 한다니. 함수가 local state를 가질 수 있다면, <strong>상태 로직을 재사용하는 방법을 보다 쉽게 바꿀 수 있지 않을까요?</strong></p><h3>What Are Hooks?</h3><p>Hooks는 바로 이런 문제를 해결합니다. 내장된 Hooks(useState, useEffect)로 함수에 state나 lifecycle 등을 제공합니다.</p><p>Hooks는 일반 JavaScript 함수입니다. 그래서 Hooks를 활용하는 Custom Hooks를 만들어 상태를 가지는 로직을 함수로 쉽게 분리할 수 있습니다. Custom Hooks 자체가 React에서 지원하는 기능이 아니지만, Hooks가 디자인 된 방식을 통해 자연스럽게 사용이 가능해지는 것입니다.</p><h3>Hooks API: useEffect, useState</h3><p>Hooks가 제공하는 내장 API에는 useEffect와 useState가 있습니다.</p><h4>useState</h4><p>useState는 함수에 state를 제공합니다. initialState를 파라미터로 받고, state와 state를 변경할 setState 함수를 반환합니다.</p><pre><em>import</em> { useState } <em>from</em> &#39;react&#39;;<br><br><em>const </em>Example = () =&gt; {<br>  <em>const</em> [count, setCount] = useState(0);<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{`count: ${count}`}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;+&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>};<br><br><em>export</em> default Example;</pre><p>useState가 반환하는 첫 번째 인자인 state와 두 번째 인자인 setState를 <a href="https://poiemaweb.com/es6-destructuring">비구조화 할당 문법</a>을 통해 count, setCount로 받아서 사용할 수 있게 됩니다. <strong>setCount로 count state를 변경하면 렌더링이 다시 일어납니다.</strong></p><p>Example은 함수이기 때문에, 렌더링 할 컴포넌트 대신에 값을 반환할 수도 있습니다.</p><pre><em>import</em> { useState } <em>from</em> &#39;react&#39;;<br><br><em>const </em>useCount = (<em>gap</em>) =&gt; {<br>  <em>const</em> [count, setCount] = useState(0);<br>  <br>  <em>const </em>increaseCount = () =&gt; {<br>    setCount(count + <em>gap</em>);<br>  }<br>  <br>  <em>const </em>decreaseCount = () =&gt; {<br>    setCount(count - <em>gap</em>);<br>  }<br>  <br>  return {<br>    count,<br>    increaseCount,<br>    decreaseCount,<br>  }<br>}<br><br><em>export</em> default useCount;</pre><p>위 예제가 바로 Custom Hook을 만든 것입니다. 이 useCount를 원하는 컴포넌트에서 호출하면 state인 count 값을 이용할 수 있고, setCount를 실행하도록 만들어진 increaseCount나 decreaseCount로 state를 변경할 수 있게 됩니다.</p><pre><em>&gt; [주의] use~는 Custom Hook의 naming rule입니다. 이 rule을 지키면 lint에서 hooks와 관련된 규칙들을 점검해줄 수 있기 때문에 따르는 것을 권장합니다.</em></pre><h4>useEffect</h4><p>componentDidMount 등 클래스 컴포넌트에 제공되었던 Life Cycle API는 useEffect로 사용할 수 있습니다. Life Cycle API에서 우리가 수행했던 API 요청, DOM 조작 등이 side effect이기 때문에, useEffect라는 이름의 API가 되었습니다.</p><p>클래스 컴포넌트에서의 componentDidMount, componentDidUpdate, componentWillUnmount가 useEffect로 실행됩니다.</p><pre><em>function </em>useEffect(<em>effect</em>: <em>EffectCallback</em>, <em>inputs</em>?: InputIdentityList)</pre><p>render가 발생할 때 마다<em>(componentDidMount: 초기, componentDUpdate: 매번) </em>effect가 실행됩니다. 두 번째 파라미터인 inputs를 통해 특정한 상태가 update 되었을 때만 effect가 실행되도록 설정할 수 있습니다.</p><pre><em>import</em> { useState, useEffect } <em>from</em> &#39;react&#39;;<br><br><em>export function </em>Data() {<br>  <em>const</em> [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    API.getData()<br>      .then((<em>response</em>) =&gt; { setData(<em>response</em>) });<br>  }, []);<br><br>  <em>const</em> isLoading = (data == null);<br>  if (isLoading) {<br>    return &#39;Loading..&#39;;<br>  }<br>  return data;<br>}</pre><p>위 예제는 useEffect의 inputs에 빈 배열을 넘겨서 최초(componentDidMount)에만 실행되도록 하였습니다. useEffect는 여러 개 사용할 수 있기 때문에 각 state마다 정의해 줄 수도 있고, 예제처럼 최초에 실행되는 것만 정의해주어도 됩니다.</p><p>componentDidMount와 componentDidUpdate의 실행방법은 알겠는데, 그럼 componentWillUnmount는 어떻게 실행할까요?</p><pre>useEffect(() =&gt; {<br>  window.addEventListener(&quot;mousemove&quot;, logMousePosition);<br>  return () =&gt; {<br>    window.removeEventListener(&quot;mousemove&quot;, logMousePosition);<br>  };<br>}, []);</pre><p>effect 함수의 return 값이 있는 경우 hook의 <strong>cleanup 함수로 인식하고 다음 effect가 실행되기 전에 실행</strong>해줍니다. componentWillUnmount는 컴포넌트가 사라지기 전에 한 번만 실행했지만, cleanup 함수는 <strong>새로운 effect 실행 전에 매번 호출</strong>된다는 차이가 있습니다.</p><p>위 예제코드에서는 inputs로 빈 배열을 넘겨주었기 때문에 unmount 될 때 한 번만 실행됩니다.</p><h3>Hooks를 사용했을 때 얻는 이점</h3><ul><li>Functional Component로 통일</li><li>Custom Hooks: 보다 쉬운 상태 로직 재사용</li><li>useEffect: 라이프 사이클 API에 흩어져있던 로직을 묶음</li></ul><p>Hooks는 HOC나 render-props 같은 패턴이 가져오는 Component Tree의 불필요한 중첩을 없애줄 수 있습니다. 복잡한 패턴을 적용하지 않고 보다 직관적으로 로직을 재사용할 수 있습니다.</p><p>뿐만 아니라 그간 함수형과 클래스형 두 가지 타입<em>(상태가 있는 경우는 클래스형 컴포넌트로, 뷰만 관리하는 경우는 함수형 컴포넌트로 개발하는 등)</em>을 오가면서 개발했던 것을 함수형 컴포넌트로 통일할 수 있습니다.</p><p>클래스형 컴포넌트에서 componentDidMount와 componentWillUnmount에 흩어져있던 관련 코드도 state 마다 묶을 수 있기 때문에 좀 더 연관성 있는 코드끼리 모을 수 있습니다.</p><h3>글을 마무리하며</h3><p>이번 글을 쓰면서 Hooks가 왜 필요한지 이해하기 위해 꽤 많은 글을 읽었습니다. 그 중 아래 Reference 첫 번째 글인 <strong>Making Sense of React Hooks</strong>가 많은 도움이 되었습니다.</p><p>미루고 미뤄왔던 Hooks에 대해 공부해서 뿌듯하지만, 이해하는데에 꽤 많이 시간이 걸렸다는 건 그 동안 상태 관련 로직을 재사용하는 것에 대해 그다지 고려해보지 않았다는 증거인 것 같아서 한편으로는 많이 반성하기도 했습니다.</p><p>Redux나 React Router가 어떤 패턴으로 만들어졌는지에 대해서도 이번 글을 정리하면서 알게 되었는데, 앞으로는 라이브러리를 쓸 때에도 사용하는 것에만 급급하기보다는 어떤 방식으로 구현되었는지 관심을 가져야겠다는 생각이 들었습니다 :)</p><p><em>Custom Hook을 활용한 Form 예제는 </em><a href="https://github.com/devSoyoung/custom-hooks-example"><em>여기</em></a><em>에서 보실 수 있습니다.</em></p><h3>Reference</h3><ul><li><a href="https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889">Making Sense of React Hooks</a></li><li><a href="https://medium.com/little-big-programming/react%EC%9D%98-%EA%B8%B0%EB%B3%B8-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8%EB%A5%BC-%EC%95%8C%EC%95%84%EB%B3%B4%EC%9E%90-92c923011818">React의 기본, 컴포넌트를 알아보자</a></li><li><a href="https://www.vobour.com/%EB%A6%AC%EC%95%A1%ED%8A%B8-react-%EC%9D%B4%ED%95%B4-4-higher-order-component">리액트(React) 이해 4 — Higher Order Component(HOC)로 컴포넌트 재사용 하기</a></li><li><a href="https://blog.naver.com/PostView.nhn?blogId=backsajang420&amp;logNo=221325867683&amp;categoryNo=77&amp;parentCategoryNo=0">[React] Render Props Pattern</a></li><li><a href="https://velog.io/@vies00/React-Hooks">React의 새로운 패러다임, React Hooks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811636d1035e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/humanscape-tech/hooks-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-usestate-useeffect-811636d1035e">Hooks 이해하기: useState, useEffect</a> was originally published in <a href="https://medium.com/humanscape-tech">None</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[selector pattern 적용 및 reselect]]></title>
            <link>https://medium.com/humanscape-tech/selector-pattern-%EC%A0%81%EC%9A%A9-%EB%B0%8F-reselect-a9a0e56c728b?source=rss-42da4571cdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9a0e56c728b</guid>
            <dc:creator><![CDATA[이소영]]></dc:creator>
            <pubDate>Fri, 09 Aug 2019 08:19:55 GMT</pubDate>
            <atom:updated>2019-08-09T08:31:55.805Z</atom:updated>
            <content:encoded><![CDATA[<p>개발중인 react-native 프로젝트에 redux와 redux-saga를 적용하게 되었습니다. 컴포넌트로부터 데이터 로직을 분리해서 더 관리하기 좋은 코드를 만들기 위함이었습니다.</p><p>프로젝트에 redux를 도입하면서 아래와 같은 절차로 데이터 요청을 수행했습니다.</p><ol><li>컴포넌트에서 <strong>FETCH_DATA</strong>액션을 dispatch합니다.</li><li>saga에서 해당 액션을 take하고 API 요청을 수행합니다.</li><li><strong>FETCH_DATA_SUCCESS </strong>액션을 dispatch해서 가져온 데이터를 store에 저장합니다.</li></ol><p>이 상황에서 컴포넌트가 가져온 데이터를 그대로 사용하거나 일부만 사용할 때에는 별로 어려움이 없었습니다. 하지만, <em>요청한 데이터를 조합</em>해서 새로운 형태로 가져오거나 <em>계산이 필요</em>한 경우 어디에서 해당 작업을 수행할지 결정하는 것이 애매했습니다.</p><p>찾아보니 오늘 글에서 소개할 <strong>selector 패턴</strong>을 통해 이 문제를 효율적으로 해결할 수 있었습니다. 오늘 글에서는 selector 패턴과 이 패턴을 더욱 효율적으로 적용할 수 있는 reselect 라이브러리에 대해서 소개하겠습니다.</p><h3>Selector</h3><p><a href="https://godsenal.github.io/2018/07/25/Redux-selector-%ED%8C%A8%ED%84%B4%EA%B3%BC-reselect/">이 글</a>에서는 store에 저장하는 액션을 <strong>setter</strong>, selector를 <strong>getter</strong>에 비유하셨습니다. <em>찾아본 글 중 가장 와닿고 이해하기 쉬운 표현이라고 생각합니다.</em></p><p><strong>selector</strong>는 store에 저장된 state에서 필요한 데이터를 선별적으로 가져오거나, 계산을 수행해서 원하는 형태의 데이터를 가져오는 일을 합니다.</p><p>컴포넌트 A와 컴포넌트 B에서 동일한 API를 요청합니다. 이 때 응답결과를 서로 다른 형태로 사용하는 경우를 생각해봅시다. 컴포넌트 A에서는 결과 중 일부를 계산해서 사용해야 하고, 컴포넌트 B에서는 응답받은 결과를 그대로 사용합니다.</p><p>컴포넌트 A만 고려하고 개발을 먼저 진행해서 응답 결과를 컴포넌트 A에 필요한 형태로 계산하여 store에 저장 했다고 생각해봅시다. 이후 컴포넌트 B를 개발할 때, store에 원래 형태의 요청결과를 가지고 있는 또 다른 필드를 추가해야 합니다. 이런 컴포넌트가 여러 개 생긴다면 store에 저장되는 데이터들이 늘어나고 관리가 어려워질 것입니다.</p><p>selector pattern을 사용하면 요청결과는 store에 저장하고, 컴포넌트에 필요한 데이터 계산(또는 조합)은 selector에게 맡기기 때문에 store를 보다 효율적으로 관리할 수 있습니다.</p><h3>Selector Example</h3><p>좀 더 쉬운 이해를 위해서 간단한 예제를 준비했습니다.</p><p>FETCH 액션으로 설문(poll) 목록 API를 요청하고 그 결과를 store에 저장하는 상황을 예시로 들어보겠습니다. <strong>MyComponent</strong>에서는 종료되지 않은 설문(<em>!poll.is_done</em>)들만 컴포넌트에 제공하고 싶습니다.</p><blockquote><strong>[주의]</strong> 아래 예제에서 <strong>rootReducer</strong> 등 redux의 기본적인 예제까지 추가하지 않았습니다. <strong>rootReducer</strong>에서 아래의 <strong>pollReducer</strong>를 <strong>combineReducer</strong>로 합쳐서 사용하는 부분은 생략되어 있습니다!</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b6dfbfa6fd3d02e1f242e3e11b69419/href">https://medium.com/media/4b6dfbfa6fd3d02e1f242e3e11b69419/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bc8e37292ce370ee94fa3ee95795486/href">https://medium.com/media/0bc8e37292ce370ee94fa3ee95795486/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07dee2d4915f31456ca7f3729999c68b/href">https://medium.com/media/07dee2d4915f31456ca7f3729999c68b/href</a></iframe><p>컴포넌트에서 props로 store의 값을 가져올 때, 만들었던 selector를 통해 가져오면 state에서 필요한 값만 가져오거나 원하는 형태로 계산해서 가져올 수 있게 됩니다. 컴포넌트마다 다른 형태로 값을 가져오더라도 selector만 관리하면 되기 때문에 store와 컴포넌트로부터 조합하는 로직을 분리할 수 있어요 :)</p><h3>Reselect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tKjjA3uxJKeirjYf_Ep7tw.jpeg" /></figure><p>하지만 저런 방식으로 selector를 사용하면 state가 변경될 때마다 selector 함수가 매번 실행됩니다. 매 state 변경마다 계산을 수행한다면 많은 데이터를 다룰 때에는 성능 문제가 발생할 수 있습니다. 이 문제를 해결해주는 것이 바로 <strong>reselect</strong>입니다.</p><p>reselect는 위의 selector 역할을 수행하면서 캐싱을 통해 동일한 계산을 방지하여 성능을 향상해줍니다. 파라미터로 전달받은 값이 이전과 같다면, 새롭게 계산하지 않고 저장된 결과 값을 돌려줍니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b606362fd3afea4b7101347a8a096c81/href">https://medium.com/media/b606362fd3afea4b7101347a8a096c81/href</a></iframe><blockquote><strong>selectFriend</strong>는 state에 friend 값이 있으면 반환하고, 없으면 friend의 초기상태를 반환하도록 예외처리를 고려해서 추가된 코드입니다.</blockquote><p>reselect도 위에서 만든 selector처럼 state를 넣어주고, state를 가공할 콜백을 전달하면 됩니다. 이렇게 만든 reselect 함수를 컴포넌트에서 import 하여 <strong>mapStateToProps</strong>에서 state를 전달해 사용하면 됩니다.</p><p>React 전문가 한 분께 여쭤보았더니 다음과 같은 경우 reselctor 도입을 고려해보면 좋을 것 같다고 말씀해주셨습니다.</p><ul><li>데이터가 많아 캐싱이나 최적화가 필요하다.</li><li>테스트 코드를 짜서 테스트를 용이하게 하고 싶다.</li><li>필요한 데이터를 주는 로직이 전부 다 서버내 구현되어 있지 않다.</li><li>받아온 데이터를 처리해야 할 로직이 많다.</li><li>서버자원을 조금 아끼고싶다. — 데이터 일정 부분 필터링, 기존 데이터 값에서 새로운 값을 계산해서 반환</li><li>컴포넌트에서 데이터를 파싱하는 로직을 추가하기 보단 파싱된 데이터를 받고 사용만하는 식으로 코드 분리를 하고싶다.</li></ul><p>redux를 적용하면서 API로 가져온 데이터를 어떻게 처리해야 할지 고민된다면, 혹은 컴포넌트마다 store에 저장된 값을 다르게 사용하고 있다면 오늘 글에서 다룬 selector pattern과 reselect에 대해 고려해보는 것을 추천드립니다. 아래에는 이 글을 작성하면서 참고했던 좋은 글들을 첨부했습니다. 시간 나실 때 함께 읽어보시면 좋을 것 같습니다 :)</p><h3>Reference</h3><ul><li><a href="http://guswnsxodlf.github.io/optimize-react-component-using-reselect">Reselect를 이용하여 React와 Redux 최적화하기</a></li><li><a href="https://medium.com/@ljs0705/redux-reselect-490f9acc1090">redux + reselect</a></li><li><a href="https://godsenal.github.io/2018/07/25/Redux-selector-%ED%8C%A8%ED%84%B4%EA%B3%BC-reselect/)%20*%20[What%20is%20a%20Redux%20selector?%E2%80%8A-%E2%80%8AMatthew%20Holman%E2%80%8A-%E2%80%8AMedium](https://medium.com/@matthew.holman/what-is-a-redux-selector-a517acee1fe8">Redux — Selector 패턴과 Reselect | Godsenal’s Blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9a0e56c728b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/humanscape-tech/selector-pattern-%EC%A0%81%EC%9A%A9-%EB%B0%8F-reselect-a9a0e56c728b">selector pattern 적용 및 reselect</a> was originally published in <a href="https://medium.com/humanscape-tech">None</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux와 미들웨어(thunk, saga)]]></title>
            <link>https://medium.com/humanscape-tech/redux%EC%99%80-%EB%AF%B8%EB%93%A4%EC%9B%A8%EC%96%B4-thunk-saga-43bb012503e4?source=rss-42da4571cdf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/43bb012503e4</guid>
            <dc:creator><![CDATA[이소영]]></dc:creator>
            <pubDate>Fri, 19 Jul 2019 06:14:15 GMT</pubDate>
            <atom:updated>2019-08-01T04:32:28.917Z</atom:updated>
            <content:encoded><![CDATA[<p>안녕하세요. 휴먼스케이프 인턴 Lily입니다 :) Redux와 Redux 미들웨어에 대해 정리한 글을 공유합니다!</p><p>대부분의 React 애플리케이션에서 Redux나 MobX 같은 상태관리 라이브러리를 사용합니다. 컴포넌트의 props와 state 만으로 상태를 관리하기엔 우리가 만드는 앱은 너무 복잡합니다. 그래서 저도 Redux를 사용했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*zTXY3OfZm5nreThL4lnu4A.png" /></figure><h3>Redux</h3><p>Redux는 Flux 패턴을 구현했습니다. MVC 패턴에서 모델과 뷰의 양방향 데이터 전달로 인해 발생하는 상태 관리의 어려움을 해결하고자 데이터의 흐름을 단방향으로 통일했습니다.</p><p><em>참고링크 : </em><a href="https://medium.com/@ljs0705/redux%EB%A5%BC-%EC%9D%B4%ED%95%B4%ED%95%98%EC%9E%90-7c9e8de0ab7f"><em>Redux를 이해하자 — landvibe — Medium</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S47DAEuMjL2qc8SratRB_g.png" /></figure><p>아래의 그림은 Flux 패턴을 검색하면 볼 수 있는 대표적인 그림입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgxTL69KXTYjupzGO015Ew.png" /></figure><p>이 Flux 패턴을 그대로 적용하면 hot-reloading 할 때 기존의 상태와 이벤트 구독이 사라진다는 문제점이 있습니다. 이를 해결하기 위해 Redux에서는 Flux의 store가 가지고 있는 <strong>상태 변환을 위한 로직</strong>과 <strong>현재 애플리케이션의 상태</strong>를 분리해서 reducer를 만들고, reducer가 상태 변환 로직을 가지도록 합니다.</p><p><em>참고링크 : </em><a href="https://bestalign.github.io/2015/10/27/redux-hot-reloading-and-time-travel-debugging/"><em>핫 리로딩(hot reloading)과 시간 여행 디버깅(time travel debugging)이 도대체 무엇일까? — bestalign’s dev blog</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*wA06Mbgf4QPqWcV6bCNfrw.png" /></figure><p>그래서 Redux는 이렇게 동작합니다. 변화가 일어나면 Action(type에 대한 정보를 가진 객체)을 만들고, (각 액션에 맞게 미리 정의해 둔) Reducer가 새로운 상태를 만들어 store를 갱신합니다. 컴포넌트(View)들은 store를 (connect()로) 구독하고 있다가 상태 변화를 반영합니다. <br> <br>Flux의 dispatcher는 Store의 dispatch 메소드로 제공됩니다. <br> <br>액션을 만들고, 그에 맞는 리듀서를 정의해서 리덕스를 적용하는 것 자체는 사실 그렇게 복잡하지 않은 것 같습니다.</p><h3><strong>Redux 예제</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336720230ae660d5c6a4f405317f4a0f/href">https://medium.com/media/336720230ae660d5c6a4f405317f4a0f/href</a></iframe><h3>Redux Middleware</h3><p>하지만 API 요청, 비동기 작업과 관련된 상태 관리를 위해 미들웨어를 적용하면서 리덕스에 대한 어려움이 기하급수적으로 증가한다고 생각합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*BHUKvOmqPjJHpRY1wp1YFw.png" /></figure><p><strong><em>미들웨어</em></strong><em> : dispatch() 메소드를 통해 store로 가고 있는 액션을 가로채는 코드</em></p><p>API 요청을 하면 REQUEST 액션을 디스패치해서 로딩 아이콘을 띄우고, 요청에 대한 처리가 완료되면 결과에 따라 SUCCESS나 FAILURE 액션을 디스패치해서 결과를 업데이트 하는 방식으로 많이 활용됩니다. <br> <br>대표적인 미들웨어는 thunk, saga 두 가지가 있습니다. 각각 스타일이 약간 다릅니다. redux와 미들웨어를 동시에 적용하면서 혼란스러웠던 경험이 있기 때문에, 두 미들웨어의 스타일에 대해 정리해보고 싶었습니다.</p><h3>Redux-thunk</h3><p>thunk 미들웨어는 객체가 아니라 함수를 반환하는 <strong>액션 생성자</strong>를 만들 수 있게 해줍니다. 특정 액션을 몇 초 후에 실행하거나, 현재 상태에 따라 액션이 실행되지 않게 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e26c70e60a19e2733780f4bccd728b4/href">https://medium.com/media/1e26c70e60a19e2733780f4bccd728b4/href</a></iframe><p>thunk를 사용하면 액션 생성자는 필요한 값을 파라미터로 받아 <strong>함수를 리턴</strong>할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dcbfe93f59ef87f2d658ed5d6e6b33e/href">https://medium.com/media/9dcbfe93f59ef87f2d658ed5d6e6b33e/href</a></iframe><p>조금 더 익숙한 형태의 코드로 쓰면 이렇게 됩니다. sec, gap을 return문에 정의된 function에서 사용하는 클로저 패턴입니다. 리턴 함수에서 getState로 현재 store의 상태를 받으면, store 상태에 따라 dispatch를 수행할지 여부도 결정할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa790f98e862736282c7fe46beb7951/href">https://medium.com/media/dfa790f98e862736282c7fe46beb7951/href</a></iframe><p><em>코드 출처 : </em><a href="https://ideveloper2.tistory.com/53"><em>React -redux thunk, redux saga</em></a></p><h3>thunk를 적용한 API 요청 예제</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66a333502c681416976fe524e1dabfe8/href">https://medium.com/media/66a333502c681416976fe524e1dabfe8/href</a></iframe><p>이 thunk 미들웨어의 단점은 action이 복잡해진다는 점입니다. 액션생성자는 type과 payload가 담긴 <strong>객체를 생성해서 반환</strong>하는 역할을 수행하기로 했는데, thunk 미들웨어에서는 API 요청이나 비동기 처리가 껴서 본래 역할이 모호해집니다. 어떨 때는 객체를 반환하고, 어떨 때는 함수를 반환합니다.</p><p><em>thunk 미들웨어와 관련된 더 자세한 내용은 </em><a href="https://codeburst.io/understanding-redux-thunk-6dbae0241817"><em>여기</em></a><em>를 참고해주세요.</em></p><h3>Redux-saga</h3><p>saga 미들웨어는 <strong>액션에 대한 리스너</strong>입니다. thunk처럼 액션 생성자가 함수를 반환하지 않고 일관되게 객체를 반환하기 때문에, 그런 부분에서 오는 모호함이 해결됩니다. ES6에서 등장한 제너레이터 문법을 사용하고 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/630977835c3b9f167006ecd3ea234071/href">https://medium.com/media/630977835c3b9f167006ecd3ea234071/href</a></iframe><p>put, call, takeLatest 외에도 몇 가지 미들웨어에서 제공하는 메소드가 있습니다. 위 코드에 나온 메소드만 간략하게 정리했습니다. 더 자세한 내용은 <a href="https://gracefullight.dev/2017/12/06/Why-redux-saga/">이 글</a>의 2–3 부분을 보시면 도움 될 것 같습니다. <br> <br><strong>put</strong> : 액션을 호출하는 dispatch()의 역할을 수행합니다. <br><strong>call</strong> : Function.prototype.call() 함수와 같습니다. <br><strong>takeLatest</strong> : 액션 호출시에 같은 액션이 실행 중이면 그 액션은 파기되고 마지막 호출만 실행됩니다. POST, PUT, DELETE 같은 리소스 변경 메소드에 사용합니다. <br><strong>takeEvery</strong> : takeLatest와 다르게 모든 액션마다 실행됩니다. GET 메소드에 사용합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e86e237dcea2bcb5f75a81454a25ea/href">https://medium.com/media/f2e86e237dcea2bcb5f75a81454a25ea/href</a></iframe><p>all()은 Promise.all()과 같습니다. yield 구문은 순차적으로 실행되기 때문에, 여러 개의 사가를 동시에 수행할 수 있도록 하기 위해 all() 메소드를 사용합니다.</p><p>이렇게 생성한 Saga는 store를 생성할 때, 미들웨어로 연결하고 실행(run())시켜주면 됩니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89d67eca023891abef594c0ba65524c3/href">https://medium.com/media/89d67eca023891abef594c0ba65524c3/href</a></iframe><p>컴포넌트에서는 Index 액션을 dispatch로 수행하면 됩니다. 저는 개인적으로 액션 생성자가 일관성있고, 역할이 제대로 분리되는 느낌이 들어서 saga가 thunk보다 편하게 느껴졌습니다.</p><p><em>saga의 경우 테스트 코드를 작성할 때에도 많은 이점이 있다고 하는데, 테스트코드는 아직 작성을 안해봐서 잘 모르겠습니다..</em></p><p>redux를 적용하기 전에, 미들웨어에 대해서도 충분히 고려해본다면 더 깔끔하고 관리하기 쉬운 코드를 만들 수 있을 것이라고 생각합니다! :)</p><p><strong>Get to know us better!<br>Join our official channels below.</strong></p><p>Telegram(EN) : <a href="https://t.me/Humanscape?source=post_page---------------------------">t.me/Humanscape</a><br>KakaoTalk(KR) : <a href="http://open.kakao.com/o/gqbUQEM?source=post_page---------------------------">open.kakao.com/o/gqbUQEM</a><br>Website : <a href="https://humanscape.io/?source=post_page---------------------------">humanscape.io</a><br>Medium : <a href="http://medium.com/humanscape-ico?source=post_page---------------------------">medium.com/humanscape-ico</a><br>Facebook : <a href="http://www.facebook.com/humanscape?source=post_page---------------------------">www.facebook.com/humanscape</a><br>Twitter : <a href="http://twitter.com/Humanscape_io?source=post_page---------------------------">twitter.com/Humanscape_io</a><br>Reddit : <a href="https://www.reddit.com/r/Humanscape_official?source=post_page---------------------------">https://www.reddit.com/r/Humanscape_official</a><br>Bitcointalk announcement : <a href="https://bit.ly/2rVsP4T?source=post_page---------------------------">https://bit.ly/2rVsP4T</a><br>Email : <a href="/service/mailto:support@humanscape.io?source=post_page---------------------------">support@humanscape.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43bb012503e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/humanscape-tech/redux%EC%99%80-%EB%AF%B8%EB%93%A4%EC%9B%A8%EC%96%B4-thunk-saga-43bb012503e4">Redux와 미들웨어(thunk, saga)</a> was originally published in <a href="https://medium.com/humanscape-tech">None</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>