<?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 bytePudding on Medium]]></title>
        <description><![CDATA[Stories by bytePudding on Medium]]></description>
        <link>https://medium.com/@bytePudding?source=rss-c1de503a1edb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bNiuE-he4Fp6IWww4vyPyA@2x.jpeg</url>
            <title>Stories by bytePudding on Medium</title>
            <link>https://medium.com/@bytePudding?source=rss-c1de503a1edb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 19:01:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bytePudding/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[Tanstack Query]]></title>
            <link>https://medium.com/@bytePudding/tanstack-query-for-work-3173c6dae9dc?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3173c6dae9dc</guid>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Wed, 20 May 2026 01:06:50 GMT</pubDate>
            <atom:updated>2026-05-20T01:07:17.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Query (TanStack Query) 개념</h3><h3>핵심 아이디어</h3><p>React Query는 <strong>“서버 상태”를 관리하는 라이브러리</strong>입니다.</p><pre>useState/useReducer  →  클라이언트 상태 (UI, 폼 등)<br>React Query          →  서버 상태 (API 데이터)</pre><p>직접 훅을 만들 때 고민했던 것들을 알아서 처리해줍니다:</p><ul><li>로딩/에러 상태</li><li>중복 요청 방지</li><li>캐싱 (같은 요청은 다시 안 함)</li><li>자동 재시도</li><li>데이터 최신화</li></ul><h3>설치</h3><pre>npm install @tanstack/react-query</pre><h3>1단계: 최상단에 Provider 설정</h3><p>frontend/src/main.tsx 또는 App.tsx:</p><pre>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;</pre><pre>const queryClient = new QueryClient();</pre><pre>function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;Router /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><h3>2단계: useQuery — 데이터 가져오기 (GET 개념)</h3><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br>import { fetchRetrieveData } from &#39;../actions/fetchRetrieveData&#39;;</pre><pre>function WordList() {<br>  const { data, error, isPending } = useQuery({<br>    queryKey: [&#39;words&#39;],              // 캐시 키 (배열)<br>    queryFn: () =&gt; fetchRetrieveData(&#39;/words&#39;, {}),<br>  });</pre><pre>  if (isPending) return &lt;div&gt;로딩중...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;에러 발생&lt;/div&gt;;</pre><pre>  return &lt;div&gt;{data}&lt;/div&gt;;<br>}</pre><p><strong>queryKey</strong>가 핵심입니다. 같은 키면 캐시된 데이터를 씁니다:</p><pre>queryKey: [&#39;words&#39;]                  // words 전체<br>queryKey: [&#39;words&#39;, userId]          // userId별로 따로 캐시<br>queryKey: [&#39;words&#39;, { page: 1 }]     // 파라미터 포함</pre><h3>3단계: useMutation — 데이터 변경 (POST/PUT/DELETE 개념)</h3><pre>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;</pre><pre>function AddWord() {<br>  const queryClient = useQueryClient();</pre><pre>  const { mutate, isPending } = useMutation({<br>    mutationFn: (newWord: string) =&gt;<br>      fetchRetrieveData(&#39;/words/add&#39;, { word: newWord }),</pre><pre>    onSuccess: () =&gt; {<br>      // 성공하면 words 캐시를 무효화 → 자동으로 재조회<br>      queryClient.invalidateQueries({ queryKey: [&#39;words&#39;] });<br>    },<br>  });</pre><pre>  return (<br>    &lt;button onClick={() =&gt; mutate(&#39;apple&#39;)} disabled={isPending}&gt;<br>      단어 추가<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>useQuery vs useMutation 구분</h3><p>useQueryuseMutation목적데이터 조회데이터 변경실행 시점컴포넌트 마운트 시 자동mutate() 호출 시해당 HTTPGET (또는 조회용 POST)POST / PUT / DELETE</p><h3>현재 프로젝트에 적용한다면</h3><p>지금 만들던 useRetrieveData 훅을 대체하면:</p><pre>// Before — 직접 만든 훅<br>const { data, error, isPending } = useRetrieveData(&#39;/words&#39;, { userId: 1 });</pre><pre>// After — React Query<br>const { data, error, isPending } = useQuery({<br>  queryKey: [&#39;words&#39;, userId],<br>  queryFn: () =&gt; fetchRetrieveData(&#39;/words&#39;, { userId }),<br>});</pre><p>fetchRetrieveData 액션 함수는 그대로 재사용할 수 있어서 actions 폴더 구조도 살아있습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3173c6dae9dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Docker Command Notes]]></title>
            <link>https://medium.com/@bytePudding/docker-commands-i-use-often-3e1e67d901c6?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e1e67d901c6</guid>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sun, 17 May 2026 10:25:08 GMT</pubDate>
            <atom:updated>2026-05-20T01:55:05.011Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Setting Container</strong></p><pre>docker run --name [container name] -- container name<br>    -e POSTGRES_USER=[username] -- db username<br>    -e POSTGRES_PASSWORD=[password] -- DB password<br>    -p 5432:5432   -- PORT ( My computer: container ) <br>    -d POSTGRES     -- image (PostgresSQL program) </pre><p>( -e : environment )</p><p><strong>Creating DB</strong></p><pre>docker exec -it [containername] psql -U [username] -d postgres -c &quot;CREATE DATABASE [dbname];&quot;</pre><p><strong>list of containers</strong></p><pre>docker ps -- currently running <br>docker ps -a -- including pended containers </pre><p><strong>starting container</strong></p><pre>docker start [containername] </pre><p><strong>list of database</strong></p><pre>docker exec -it [containerName] psql -U [userName] -c “\l”</pre><p><strong>list of table</strong></p><pre>docker exec -it [containername] psql -U myuser -d [postgreSQL DB name] -c &quot;\dt&quot;</pre><p><strong>Prisma migrate</strong></p><pre>npx prisma migrate dev --name [changes]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e1e67d901c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why My Work Went Wrong Today: Analyzing the Cursor Error]]></title>
            <link>https://medium.com/@bytePudding/why-my-work-went-wrong-today-analyzing-the-cursor-error-f4fd19d83436?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4fd19d83436</guid>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[oracle]]></category>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 13:52:21 GMT</pubDate>
            <atom:updated>2025-11-26T04:26:30.811Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Table of Contents</strong></p><p>· <a href="#67ae">At Work</a><br>· <a href="#f30e">Analyzing the Cursor</a><br> ∘ <a href="#5207">Explicit Cursor </a><br> ∘ <a href="#c446">Process </a><br> ∘ <a href="#9fda">Declaring </a><br> ∘ <a href="#b2e0">Opening </a><br> ∘ <a href="#4e3f">Fetching</a><br> ∘ <a href="#ffb2">Closing </a><br> ∘ <a href="#194d">Attributes</a><br> ∘ <a href="#a7c9">SQL</a></p><h3>At Work</h3><p>So today, I got a task to create a procedure using a<strong> double for-loop</strong> and a <strong>DML/SELECT that was written as a literal statement</strong> like ‘select emp_id from employees’.<br>I looked online and saw that I couldn’t use a regular cursor for that, but needed to use a REF CURSOR or a record type instead. So far, so good ! At least that’s what I thought.</p><p>But my code kept throwing errors over and over.</p><p>After digging into it, I finally realized the problem:<br><em>I had placed the FETCH statement before the LOOP.</em></p><p>A <strong>FETCH </strong>statement actually retrieves a row from the opened cursor — so putting it before the loop meant<strong> I was consuming the first row without processing it</strong>. I couldn’t figure this out earlier simply because I didn’t fully understand how cursors work.</p><p>As a bit of retrospect, I reviewed everything about cursor structure, FETCH flow, and dynamic SQL.<br>Hopefully I’ll do better tomorrow !!</p><h3>Analyzing the Cursor</h3><h4>Explicit Cursor</h4><p>Every SQL statement executed by Oracle server has an individual cursor :</p><ul><li>Implicit Cursors : Managed by PL/SQL for all DML select statements</li><li><strong>Explicit Cursors</strong> : Managed by <em>Programmer</em></li></ul><p>Explicit Cursor can perform<strong> row-by-row</strong> processing beyond the first row returned by a query</p><h4>Process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVahkE9X-NHFkdrw65AJAQ.png" /></figure><h4>Declaring</h4><pre>DECLARE CURSOR c_rec is<br> SELECT pay_item_cd , emp_id FROM PAY_PAYROLL;       </pre><ul><li><strong>Do not include INTO clause</strong> in the cursor declaration because it appears in the FETCH statement</li></ul><h4>Opening</h4><pre>DECLARE CURSOR c_rec is<br> SELECT pay_item_cd , emp_id FROM PAY_PAYROLL;<br>...<br> BEGIN <br>   OPEN c_rec;</pre><ul><li><strong>The OPEN statement executes the query associated with the cursor, identifies the active set, and positions the cursor pointer at the first row.</strong></li></ul><p>It does following operations :</p><ol><li>Dynamically allocates memory for a context area</li><li>Parses the SELECT statement</li><li>Binds the input variables( sets the values for the input variables by obtaining memory address)</li><li>Identify the active set( the set of rows that satisfiy the search criteria). Rows in the active set are not retrieved into variables when the OPEN statement ist executed. Rather, the FETCH statement.</li><li>Positions the pointer to the first row in the active set</li></ol><p><strong>Note </strong>: If a query returns no rows, PL/SQL does not raise an exception. You can find out number of rows by using &lt;cursor_name&gt;%ROWCOUNT attribute</p><h4>Fetching</h4><ol><li>Reads the data for the current row into the output PL/SQL variables</li><li>Advances the pointer to the next row in the active set</li></ol><h4>Closing</h4><ul><li>It disables the cursor, release the context area, and undefines the active set.</li><li>Cursor can only be reopened if it is closed</li><li>PL/SQL will terminate the cursor but you should make it a habit to close any cursor that you declare explicitly to free up resources.</li></ul><h4>Attributes</h4><p><strong>%ISOPEN</strong> : Evaluates TRUE if the cursor is open</p><p><strong>%NOTFOUND</strong> : Evaluates to TRUE if the most recent fetch does not return a row</p><p><strong>%FOUND</strong> : Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND</p><p><strong>%ROWCOUNT</strong> : Evaluates to the total number of rows returned so far</p><h4>SQL</h4><ol><li><strong>Basic</strong></li></ol><pre>DECLARE<br>    CURSOR c_emp_dept30 is <br>     select employee_id, first_name from employees where department_id = 30;<br>    <br>    v_emp_rec employees%rowtype;<br>    <br>BEGIN<br>   -- opening<br>   OPEN c_emp_dept30;<br>   <br>   LOOP<br><br>    -- fetching  <br>    FETCH c_emp_dept30 into v_emp_rec.employee_id, v_emp_rec.first_name;<br>     exit when c_emp_dept30%NOTFOUND;<br><br>   END LOOP;<br>   <br>   -- closing <br>   close c_emp_dept30;<br>END;</pre><p><strong>2. using Attribute</strong></p><pre>DECLARE<br>    CURSOR c_emp IS <br>    SELECT employee_id, first_name FROM employees;<br><br>    v_emp_no employees.employee_id%type;<br>    v_first_name employees.first_name%type;<br>    <br>BEGIN <br>    -- if cursor is opened, dont do anything <br>    if c_emp%isopen then <br>    null;<br>    else<br>    open c_emp;<br>    end if;<br>       dbms_output.put_line(c_emp%ROWCOUNT); -- return 0 cuz no cursor is fetched <br>    loop<br>        fetch c_emp into v_empno , v_first_name;<br>        exit when c_emp%not_found or c_emp%rowcount&gt; 10; -- exit when cursor no found , or rowcount over 10<br>        dbms_output.put_line(v_empno);<br>    end loop;<br><br>   close c_emp;<br>END;</pre><p><strong>3. For Loop cursor</strong></p><pre>-- method 1 <br>declare <br>   CURSOR c_emp_dept30 is<br>     select employee_id, first_name from employees<br>     where department_id = 30;<br>BEGIN <br>    <br>    for i in c_emp_dept30<br>    loop <br>        dbms_output.put_line(i.employee_id);<br>    end loop;<br>END;<br><br><br>-- method 2 (no need to declare cursor) <br>DECLARE<br><br>BEGIN <br>    <br>    for i in ( select employee_id, first_name <br>                 from employees<br>                where department_id = 30)<br>    <br>    loop <br>        dbms_output.put_line(i.employee_id);<br>    end loop;<br><br>END;</pre><ul><li>no need to fetch, open or close</li></ul><p><strong>4. Parameter</strong></p><pre>DECLARE<br>    CURSOR c_emp_dept(v_dept number) -- define the parameter without size <br>    is <br>    SELECT employee_id, first_name FROM employees<br>    where department_id = v_dept;<br>    <br>    v_emp_no employees.employee_id%type;<br>    v_first_name employees.first_name%type;<br>    <br>BEGIN <br>    OPEN c_emp_dept(10); -- 10 will go to the parameter(v_dept)<br>    loop <br>        fetch c_emp_dept into v_emp_no, v_first_name;<br>        exit when c_emp_dept%notfound;<br>        dbms_output.put_line(v_emp_no); -- employees from department 10 <br>    end loop;<br>    close c_emp_dept;<br>    <br>    OPEN c_emp_dept(20); -- 20 will go to the parameter(v_dept)<br>    loop <br>        fetch c_emp_dept into v_emp_no, v_first_name;<br>        exit when c_emp_dept%notfound;<br>        dbms_output.put_line(v_emp_no); -- employees from deparment 20<br>    end loop;<br>    close c_emp_dept;<br>END;</pre><p><strong>5. FOR UPDATE clause &amp; CURRENT OF clause</strong></p><p>‘using for update’ at the end of the DML , reserve the result for your session</p><pre><br>select * from employees<br>where employee_id in (100,200)<br>for update; -- reserve result for your session (other sessions cant to do dml)<br><br></pre><p>we can use this in our cursor</p><pre>DECLARE <br>    CURSOR c_emp_dept30 is <br>    SELECT employee_id, first_name, salary FROM employees<br>    where department_id = 30<br>    for update;  -- Oracle allows using WHERE CURRENT OF with this<br>     <br>BEGIN <br>    for i in c_emp_dept30<br>    loop <br>        update employee<br>          set salary = salary + 1<br>        -- Normally we would do:<br>       -- where employee_id = i.employee_id;<br>        where current of c_emp_dept30; -- Directly updates the current row<br>    end loop;<br>    commit;<br>END;</pre><p>When we use the FOR UPDATE clause in a cursor, we can apply WHERE CURRENT OF to update the exact row that the cursor is currently pointing to.</p><p>This becomes especially useful when a table has complex primary keys or multiple key columns, because you don’t need to manually specify every condition in the WHERE clause.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4fd19d83436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Networking : Router]]></title>
            <link>https://medium.com/@bytePudding/networking-mac-address-and-switches-e31a70702f56?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e31a70702f56</guid>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 13:37:57 GMT</pubDate>
            <atom:updated>2025-11-09T13:39:06.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Networking : Router</h3><p>Routers and how internet works…</p><h3>Switch vs Router</h3><p>When we connect multiple devices inside the <strong>same place like computers, TVs or printers in our home. We often just use switch.</strong></p><p>A switch simply connects devices that are on the same local network, and they communicate using unique <strong>MAC addresses.</strong></p><p>But what If I want to connect someone outside my country?</p><p>That’s where a <strong>router</strong> comes in.</p><p>A router <strong>connects different networks </strong>together. It has unique <strong>IP addresses</strong> and uses that address to communicate across long distances, even between countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFhfv0i-pXS6eqJJPgTG6A.png" /></figure><p>In modern days, switches and routers are usually combined in a single device.</p><h3>IP Addresses</h3><p>An IP address works like a home address</p><ul><li>Part of represents the network</li><li>Part of represents the specific device</li></ul><p>For example</p><pre>32.10.0.1<br>32.10.0.11</pre><p>There two devices are in the same network (32.10.x.x) but have different host addresses.</p><h3>Global Communication</h3><p>When I (in Korea) chat with someone in Germany, our computers are actually connected through a giant chain of routers around the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*zEMp60_LmADAslxC.jpg" /><figcaption><a href="https://spie.org/news/photonics-focus/septoct-2021/fiber-optic-cables-enable-deep-ocean-science">https://spie.org/news/photonics-focus/septoct-2021/fiber-optic-cables-enable-deep-ocean-science</a></figcaption></figure><p>Accross oceans, submarine cables carry data (bits : zeros and ones) to international network, allowing routers to find the correct IP address.</p><h3>ISP ( Internet Service Provider )</h3><p>Even we have a router at home, we cannot access the internet directly.</p><p>To connect to the global network, we need an ISP(Internet Service Provider).</p><p>The ISP gives our router a public IP address and connects our home to the huge worldwide network of other routers and servers.</p><p>So when we buy an internet plan, we are paying an ISP to give us access to the internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e31a70702f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Networking : MAC address and Switches]]></title>
            <link>https://medium.com/@bytePudding/networking-mac-address-and-switches-2fe04f0629b7?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe04f0629b7</guid>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 05:48:05 GMT</pubDate>
            <atom:updated>2025-11-02T05:48:05.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>Networking : MAC address and Switches</h3><p>This writing is a summary of one of the networking classes from <em>Understanding Node.js: Core Concepts</em> by<strong> </strong><a href="https://www.udemy.com/user/joseph-heidari-3/">Joseph Heidari</a></p><h3>Table of Contents</h3><p>· <a href="#a3df">Before Networking Technology Was Developed </a><br>· <a href="#4157">After Networking Technology Was Developed </a><br> ∘ <a href="#b0d1">Switch</a></p><h3>Before Networking Technology Was Developed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-X4AQUndOY11vRG5Q6RqJA.png" /></figure><p>Before networking technology (like switches) was developed, it was impossible to send data directly to another computer.<br>Therefore, to transfer data,<strong> people had to store it on physical media such as floppy disks and the receiver had to load on their own computer.</strong></p><h3>After Networking Technology Was Developed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkrP0hC5Zrb1lI0lWtBbyw.png" /></figure><p>After <strong>switches </strong>were developed, as long as a computer was connected to the switch, it became possible to send data (packets) to another computer without using floppy disks.</p><h4>Switch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaMYGN4A4us61AGb" /><figcaption>Photo by <a href="https://unsplash.com/@albertstoynov?utm_source=medium&amp;utm_medium=referral">Albert Stoynov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To use a switch, we use an Ethernet cable to connect the computer to the switch. The switch checks each computer’s unique ID (called a MAC address) and sends data packets based on that ID.</p><p>Each computer has its built in Networking Card. In that card, it contains its unique MAC address (48 bits)</p><p>This is unique to every computer. once is exposed, it can be eaily hacked so becareful!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*CSNqAgRVaocCCj7spGfYLQ.png" /><figcaption>You can check your MAC address from your computer setting</figcaption></figure><p>When we send data to another computer, we are sending a packet to the switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhoAEEZnulybmZU22uILzA.png" /></figure><p>The diagram above is a simplified version of a packet , there’s actually more to it than that!</p><p>The important parts of a packet here are:<br>the <strong>Source</strong>, which is the sender’s MAC address,<br>the <strong>Destination</strong>, which is the receiver’s MAC address,<br>and the <strong>Data</strong> itself.</p><p><strong>The switch receives this packet, checks the destination, and sends the packet to the computer that has the corresponding MAC address.</strong></p><p>This is how Networking works using Switch !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe04f0629b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Accurately Set transformOrigin with GSAP]]></title>
            <link>https://medium.com/@bytePudding/how-to-accurately-set-transformorigin-with-gsap-00f12748880d?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/00f12748880d</guid>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 15:23:57 GMT</pubDate>
            <atom:updated>2025-07-05T16:00:34.708Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with GSAP animations, there are times when you want an element to <strong>rotate or scale from a specific point</strong> — not just its center. That’s where the transformOrigin property comes in.</p><p>By default, transformOrigin is set to “center center”. However, it actually calculates from the <strong>top-left corner</strong> of the element. So if you want to rotate something from a custom point — like the <strong>rear tire of a truck</strong> — you&#39;ll need to provide the exact coordinates <strong>relative to the top-left corner</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*RJ9XJ0hKoJb16tfDC_5LJQ.png" /></figure><p>As picture above, I wanna rotate the truck from the rear of the tire.</p><p>To do that, we have to calculate the distance from left-top to the target point</p><pre>//html <br>&lt;img class=&quot;truck&quot; src=&quot;...&quot; alt=&quot;&quot; /&gt;<br><br>// animation code <br>const t = gsap.to(&quot;.truck&quot;, {<br> transformOrigin:&quot;65px 160px&quot;, rotation:-40, repeat:1, yoyo:true}) <br>// 65px 160px is the position of the target point<br>demo.addEventListener(&quot;click&quot;, () =&gt; t.restart())<br><br><br>// checking the position of target when clicked <br>document.querySelector(&#39;.truck&#39;).onclick = function(e) {<br>      var rect = e.target.getBoundingClientRect();<br>      var x = e.clientX - rect.left; //x position within the element.<br>      var y = e.clientY - rect.top;  //y position within the element.<br>      console.log(x, y);<br>}<br></pre><ul><li>getBoundingClient() gives the position and size of the element <strong>relative to the viewport</strong>.</li><li>e.clientX and e.clientY are also relative to the viewport.</li><li>So, to get the <strong>position inside the element</strong>, we subtract the element’s left/top position from the click coordinates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*15Y6RMXgf-RMXvFr5TENIQ.png" /></figure><p>Now, when you click on the <strong>desired pivot point (e.g. the center of the wheel)</strong>, the console will show the exact pixel coordinates relative to the element’s top-left corner. You can then plug those numbers into transformOrigin</p><p>full code here :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsnorkltv%2Fembed%2Fpreview%2FWNaybbo%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DWNaybbo&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsnorkltv%2Fpen%2FWNaybbo&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FWNaybbo-512.jpg%3Fversion%3D1683927012&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4802ee4382014661620377e314ca969/href">https://medium.com/media/b4802ee4382014661620377e314ca969/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00f12748880d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router와 React Query 통합하기]]></title>
            <link>https://medium.com/@bytePudding/react-router%EC%99%80-react-query-%ED%86%B5%ED%95%A9%ED%95%98%EA%B8%B0-f0a263a688b3?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0a263a688b3</guid>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 06:28:23 GMT</pubDate>
            <atom:updated>2025-06-08T06:28:23.766Z</atom:updated>
            <content:encoded><![CDATA[<p>React Router (v6.4)와 React Query를 통합하는 방식을 정리한 글이다.</p><h4>Table of Contents <br>· <a href="#73be">기본설정 </a><br>· <a href="#761f">데이터 로딩 패턴 </a><br> ∘ <a href="#0eb4">문제점 </a><br> ∘ <a href="#63fb">해결책</a></h4><p><strong>기본설정</strong></p><pre>import {QueryClientProvider} from &#39;@tanstack/react-query&#39;;<br>import { RouterProvider } from &#39;react-router-dom&#39;;<br><br><br>function App(){<br>  return (<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;RouterProvider router={router} /&gt;<br>      &lt;/QueryClientProvider&gt;<br><br>    )<br>}</pre><ul><li><strong>QueryClientProvider</strong>는 React Query의 컨텍스트를 제공</li><li><strong>queryClient</strong>는 애플리케이션 전체에서 공유되는 쿼리 클라이언트 인스턴스 ( const queryClient = new QueryClient() )</li><li><strong>RouterProvider</strong>는 React Router의<strong> </strong>라우터 기능을 제공</li><li>이 두 Provider를 함께 사용하여 데이터 관리(React Query)와 라우팅을 통합</li></ul><h3><strong>데이터 로딩 패턴</strong></h3><pre>export function loader({params}){<br>  return queryClient.fetchQuery({<br>      queryKey : [&#39;events&#39;, params.id],<br>      queryFn : ({signal}) =&gt; fetchEvent({signal, id: params.id})<br>   })<br>}</pre><ul><li>loader는 페이지가 <strong>랜더링되기 전</strong>에 실행되는 React Router 함수이며, queryClient.fetchQuery는 React Query를 통해 데이터를 가져오고 캐시에 저장하는 메서드이다.</li><li>이 두 가지를 결합함으로서 페이지 전환 시 미리 데이터를 로드하고, 이후 빠르게 보여줄 수 있다.</li></ul><h4><strong>문제점</strong></h4><pre>// 1. 컴포넌트가 로드되기 전 React Router의 loader<br>loader({ params }) =&gt; queryClient.fetchQuery({...});<br><br>// 2. 컴포넌트 안<br>useQuery({ queryKey: [&#39;events&#39;, params.id], queryFn: ... });</pre><ul><li><strong>loader</strong>는<strong> 페이지 진입 전 </strong>데이터를 fetch한다</li><li><strong>useQuery</strong>는 <strong>컴포넌트가 mount</strong>되면 데이터를 fetch한다</li></ul><p><strong>=&gt; 이 둘이 같은 데이터를 동시에 요청할 가능성이 있다.</strong></p><h4><strong>해결책</strong></h4><p><strong>컴포넌트</strong> <strong>내부</strong>의 useQuery에 <strong>staleTime</strong>을 설정해준다</p><pre>const {data} = useQuery({<br>    queryKey : [&#39;events&#39;, params.id],<br>    queryFn : ({signal}) =&gt; fetchEvent({signal, id : params.id}),<br>    staleTime : 1000, // 1초가 지나면 stale(오래된) 상태가 됨<br>                      // 즉 1초 전에는 fresh한 상태<br>})</pre><p>React Query는 기본적으로 staleTime : 0 이다. 즉, <strong>캐시가 있더라도 항상 stale(낡았다고) 가정</strong>하기 때문에, 컴포넌트가 마운트되면 즉시 네트워크 요청을 한다.</p><p><strong>staleTime을 설정</strong>함으로써, React Query는 이 데이터가 fresh하다고 판단한다. 따라서 useQuery는<strong> loader에서 받아온 캐시된 데이터를 즉시 사용</strong>하고, 네트워크 요청을 다시 보내지 않는다.</p><p><em>그러면, 1초가 지나면 자동으로 fetch를 실행하는건가?</em></p><p>그건 또 아니다.<strong> stale이 되었다는 것과 곧바로 다시 요청하는 것은 다르다.</strong></p><p>React Query에서 stale 상태란, 해당 데이터가 오래됐다(stale)라고 표시만 하는거다. 이건 자동으로 다시 요청하지 않다. 다시 요청될 때는 , 컴포넌트가 다시 마운트 되거나, queryKey가 변경될 때 등 일반적으로 예상할 수 있는 상황에서 발생한다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0a263a688b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[낙관적 업데이트를 활용한 React Query Mutation]]></title>
            <link>https://medium.com/@bytePudding/%EB%82%99%EA%B4%80%EC%A0%81-%EC%97%85%EB%8D%B0%EC%9D%B4%ED%8A%B8%EB%A5%BC-%ED%99%9C%EC%9A%A9%ED%95%9C-react-query-mutation-ecfe1e801996?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecfe1e801996</guid>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 04:11:17 GMT</pubDate>
            <atom:updated>2025-06-08T04:11:17.898Z</atom:updated>
            <content:encoded><![CDATA[<p>이 글은 유데미 리엑트 강의 이해를 위해 작성한 글입니다.</p><h4><strong>낙관적 업데이트(Optimistic Update)는 무엇인가?</strong></h4><p>useOptimistic처럼 <strong>mutation이 성공할 것이라고 가정</strong>하고, <strong>서버에 응답을 받기전에 로컬상태를 업데이트 </strong>하는 것을 말한다.</p><p>강의에서는 이벤트 페이지를 수정하는 컴포넌트에 사용했다.</p><h4>단계</h4><ol><li><strong>Mutation 설정</strong></li></ol><pre>const { mutate } = useMutation({ mutationFn : updateEvent });</pre><ul><li>React Query의 useMutation hook이다.</li><li><strong>updateEvent</strong>는 이벤트를 업데이트하기 위한 API 이다.</li><li><strong>mutate</strong>는 업데이트 실행할 때 부른다.</li></ul><p><strong>2. 낙관적 업데이트 설정</strong></p><pre>onMutate : async (data) =&gt; {<br>   const newEvent = data.event;<br>   // 1. 쿼리취소<br>   await queryClient.cancelQueries({queryKey : [&#39;events&#39;, params.id]});<br>   // 2. 이전 캐시저장 <br>   const previousEvent = queryClient.getQueryData([&#39;events&#39;, params.id]);<br>   // 3. 낙관적 업데이트 <br>   queryClient.setQueryData([&#39;events&#39;, params.id], newEvent)<br><br>  // 4. Rollback대비, 이전 캐시리턴 <br>  return { previousEvent }<br>}</pre><ul><li>낙관적 업데이트 전략이다. 즉, <strong>서버에서 응답 받기 전에 UI를 업데이트 시켜준다.</strong></li><li>맨 처음 <strong>queryClient.cancelQueries</strong>를 이용하여 해당 이벤트([‘events’, params.id]) 에 대한 쿼리진행을 취소(cancel)한다. 이는 동시에 진행중인 refatch등을 막기 위함이다.</li><li>Rollback 상황을 대비하여, 현재 캐시에 저장된 이전데이터를 getQueryData를 통해 가져온다.</li><li><strong>queryClient.setQueryData를 사용해 캐시에 있는 데이터를 새 이벤트 값으로 먼저 업데이트 한다. =&gt; 여기서 [‘events’, params.id] 키를 가진 캐시가 즉시 새 데이터로 바뀐다.</strong></li><li>나중에 서버 요청이 실패할 경우, 캐시가 업데이트 되기 전의 상태의 값(previousEvent)을 반환하여 기존 상태로 돌아갈 수 있도록 한다.</li></ul><p>여기서 낙관적 업데이트가 이루어지는 부분은 <strong>queryClient.setQueriesData([키], 낙관적데이터)</strong> 이다. 이 시점에서 <strong>서버 응답을 기다리지 않고</strong> 캐시를 먼저 업데이트 시켜버린다.</p><p>서버 응답이 오면, useMutation의 onSuccess에서 보통queryClient.<strong>invalidateQueries</strong>(…)를 호출하여 관련 데이터를 서버에서 다시 fetch하도록 한다. 이 과정에서 <strong>서버 응답값이 새로운 캐시에 덮어씌워지게 되어</strong>, UI는 최종적으로 서버의 실제 데이터와 동기화된다.</p><p>만약에 invalidateQueries를 진행하지 않으면, 캐시는 서버 응답으로 갱신되지 않고 낙관적 업데이트 상태가 계속 유지된다. 따라서 onSucess 또는 onError에서 적절히 invalidate하거나 rollback 시켜서 이전 캐시 데이터로 덮어씌운다.</p><p><strong>3. 에러 핸들링</strong></p><pre>onError : (error, data, context) =&gt; {<br>      queryClient.setQueriesData([&#39;events&#39;, params.id]<br>                                 , context.previousEvent])<br>}</pre><ul><li>업데이트에 실패한다면, 이전 데이터로 rollback 시킨다.</li><li>onMutate의 리턴값이 context의 값으로 들어가게 된다.</li></ul><p><strong>4. 클린업</strong></p><pre>onSettled : () =&gt; {<br>    queryClient.invalidateQueries([&#39;events&#39;, params.id])<br>}</pre><ul><li>실패하든 성공하든 진행된다.</li><li>쿼리를 invalidate(무효화) 시켜서 다시 실행되게 한다.</li><li>UI는 가장 새로운 데이터를 볼 수 있다.</li></ul><p><strong>전체코드</strong></p><pre><br> const { mutate } =  useMutation({<br>   // 비동기 작업 함수 (POST, PUT, DELETE) <br>    mutationFn : updateEvent,<br><br>    // 낙관적 업데이트<br>    onMutate : async (data) =&gt; {<br>      const newEvent = data.event;<br>       // 1.쿼리 취소<br>      await queryClient.cancelQueries({queryKey : [&#39;events&#39;, params.id]});<br>       // 2. 이전 캐시 저장 <br>      const previousEvent = queryClient.getQueryData([&#39;events&#39;, params.id]);<br>        // 3. 캐시 즉시 업데이트 <br>      queryClient.setQueryData([&#39;events&#39;, params.id], newEvent);<br>      // 4. 이전 캐시 리턴 (Rollback대비) <br>      return { previousEvent}<br>    }, <br><br>    // 에러핸들링 <br>    onError : (error, data, context) =&gt; {<br>        queryClient.setQueriesData([&#39;events&#39;, params.id], context.previousEvent);<br>    },<br><br>    // 클린업 (실패 or성공여부 상관없이 최신데이터 동기화) <br>    onSettled : () =&gt; {<br>      queryClient.invalidateQueries([&#39;events&#39;, params.id])<br>    }<br>  })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecfe1e801996" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Async Logic in React with Thunks]]></title>
            <link>https://medium.com/@bytePudding/managing-async-logic-in-react-with-thunks-2abc0fae87b8?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2abc0fae87b8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[thunk]]></category>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sat, 10 May 2025 13:32:52 GMT</pubDate>
            <atom:updated>2025-05-12T04:30:34.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tjJyF14QMoVOKidH" /><figcaption>Photo by <a href="https://unsplash.com/@matthewhenry?utm_source=medium&amp;utm_medium=referral">Matthew Henry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>This post is based on the React course by </em><a href="https://www.udemy.com/user/academind/"><strong><em>Maximilian Schwarzmüller</em></strong></a><em>. Some of the code snippets are directly taken or adapted from the course content.</em></blockquote><p>When we need to send data to the backend server, we can’t use async function inside in redux reducers ( createSlice ). Because it must be <strong>pure functions</strong> ( Can’t have side effects and async )</p><p>To solve this issue, one of the best pattern we can approach is using <strong>useEffect + Thunk</strong></p><p><strong>cart-slice.js</strong></p><pre>export const sendCartData = (cart) =&gt; {<br>  return async (dispatch) =&gt; {<br>      // async logic .. <br>   }<br>}</pre><p><strong>App.js</strong></p><pre>const cart = useSelector(state =&gt; state.cart);<br><br>useEffect(() =&gt; {<br>  dispatch(sendCartData(cart)); // using thunk functions <br>}, [cart]);</pre><p>Just by doing it , it clears seperations of concerns</p><ul><li><strong>useEffect</strong> watches for changes</li><li><strong>Thunk </strong>handles the async logic (because normal function will execute right away ! )</li><li><strong>Redux</strong> manages the state</li></ul><p>Then I came to this question , <strong>what is thunk ??</strong></p><pre>const addToCart = (item) =&gt; {<br>    return async (dispatch) =&gt; {<br>        try {<br>            await saveToInternet(item);<br>            dispatch({<br>                type: &#39;ADD_TO_CART&#39;,<br>                payload: item<br>            });<br>        } catch (error) {<br>            dispatch({<br>                type: &#39;ADD_TO_CART_ERROR&#39;,<br>                payload: error<br>            });<br>        }<br>    }<br>}</pre><p>This is a <strong>thunk</strong> because :</p><ul><li>it returns<strong> another function</strong></li><li>that function takes <strong>dispatch</strong></li></ul><p>A <strong>thunk function</strong> refers to a <strong>function that wraps an expression to delay its evaluation</strong>.</p><p>I also was curious why this <strong>thunk</strong> has a <strong>dispatch </strong>as an argument ?</p><pre>const sendCartData = (cart) =&gt; {<br>  return async (dispatch) =&gt; { // &lt;--- why this dispatch?? <br>      // logic... <br>  }<br>}<br><br>dispatch(sendCartData(cart));</pre><ol><li>First, sendCartData(cart) runs and returns a <strong>function</strong></li></ol><pre>async (dispatch) =&gt; {<br>    // async logic.. <br>}</pre><p>2. Then <strong>Redux </strong>sees this function and says :</p><ul><li>Oh ! This is a thunk function !</li><li>I’ll <strong>give it the dispatch function</strong> so it can dispatch actions</li><li>And <strong>I’ll </strong>run it for you</li></ul><p>This is what happening internally.</p><p>Lastly, Let’s compare Normal function and Thunk function one more time 😺</p><pre>// normal function <br>const orderFood = () =&gt; {  return {type : &quot;ORDER_FOOD&quot; } }<br>// This is like saying &quot;I WANT FOOD !!!! &quot; but I CANT WAIT FOR IT <br><br><br>// thunk function <br>const orderFood = () =&gt; {<br>  return async (dispatch) =&gt; {<br>      dispatch({type : &quot;MENU_SCANNING&quot;}) // checking menu;<br><br>      await cookFood(); // cooking food <br>      <br>      dispatch({type : &quot;ROOD_READY&quot;}); // food is ready ! <br><br>  }<br><br>}</pre><h3>Conclusion</h3><p>By using thunk for handling async in Redux , we can use async in Redux and manages our state organized !</p><p><a href="https://github.com/puddingForever/learn-redux">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2abc0fae87b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux와 사용법]]></title>
            <link>https://medium.com/@bytePudding/redux%EC%99%80-%EC%82%AC%EC%9A%A9%EB%B2%95-3dcf107460f7?source=rss-c1de503a1edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dcf107460f7</guid>
            <category><![CDATA[리덕스]]></category>
            <dc:creator><![CDATA[bytePudding]]></dc:creator>
            <pubDate>Sat, 10 May 2025 04:29:06 GMT</pubDate>
            <atom:updated>2025-05-10T06:36:49.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y5cNVvFJ-i2BcE6C" /><figcaption>Photo by <a href="https://unsplash.com/@katiemoum?utm_source=medium&amp;utm_medium=referral">Katie Moum</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Table Of Contents</h3><p>· <a href="#acef">Redux </a><br> ∘ <a href="#c397">Store — 빵집의 장부 </a><br> ∘ <a href="#c3b1">Reducer —가게 규칙 </a><br> ∘ <a href="#0f37">Actions — 직원들에게 명령하기 </a><br>· <a href="#a100">Redux Toolkit </a><br> ∘ <a href="#28ff">Store — 전역데이터 저장소 </a><br> ∘ <a href="#dd04">Reducer — 데이터를 바꾸는 규칙 </a><br> ∘ <a href="#485f">Action -명령 </a><br>· <a href="#4c84">파일 관리법 </a><br>· <a href="#05ec">핵심개념</a></p><h3>Redux</h3><p>리덕스는 간단히 말해 <strong>상태 관리 라이브러리</strong>로, 시스템이 중앙에서 모든 것을 관리하는 구조를 가지고 있다.</p><p>이를 쉽게 설명하자면, 마치 모든 결정이 한 곳에서 이루어지는 중앙 집중식 가게나 엄격한 정부와 같다. 아래는 프레첼을 파는 빵집으로 예시를 만들어봤다.</p><h4>Store — 빵집의 장부</h4><p>공식적인 모든 프레첼은(state) 이 곳에서만 관리된다. 다른 곳에서는 관리할 수 없다. 즉 빵집의 장부임</p><pre>const store = createStore(bakeryReducer);</pre><h4>Reducer —가게 규칙</h4><p>가게 운영 방침을 적어두는 곳이다. 가게 직원들은 아래 규칙을 따라야한다.</p><pre>const bakeryReducer = (state = { pretzels : 0, isOpen : false} , action) =&gt; {<br>  <br>    if(action.type === &quot;SELL_PRETZEL&quot;) {<br>          return { pretzels : state.pretzels ++ , isOpen : state.isOpen }<br>      }<br><br>    if(action.type === &quot;OPEN_STORE&quot;){<br>        return { isOpen : true , pretzels : state.pretzels }<br>    }<br><br>  return state;<br><br>}</pre><h4>Actions — 직원들에게 명령하기</h4><pre>dispatch({ type : &quot;SELL_PRETZEL&quot;}); <br>dispatch({ type : &quot;OPEN_STORE&quot; });</pre><h3>Redux Toolkit</h3><p>기존 Redux를 더 편하게 사용할 수 있다.</p><h4>Store — 전역데이터 저장소</h4><pre>const store = configureStore({<br>  reducer : {<br>            bakery: backerySlice.reducer,<br>            parkingLot : parkinglotSlice.reducer<br>        }<br>})<br><br>export default store;</pre><p>createStore는 conbimeReducers()를 사용하지 않는이상 오직 하나의 reducer만 넣을 수 있었음.<strong> configureStore는 여러개의 reducer를 바로 넣을 수 있다.</strong></p><h4>Reducer — 데이터를 바꾸는 규칙</h4><pre>export default const bakerySlice = createSlice({<br>  name : &#39;bakery&#39;,<br>  initialState : {pretzels : 10, isOpen : false},<br>  reducers : {<br>      bakePretzel(state){ state.pretzels += 1 } ,<br>      isOpen(state){ state.isOpen = true}<br>  }<br>})<br><br>// disaptch에 사용할 actions들을 모아서 보냄 <br>export const bakeryActions= bakerySlice.actions;</pre><p>기존 Redux에서는 상태(state)를 직접 변경(mutate)하는 것이 금지되어 있었기 때문에, 항상 새로운 객체를 반환해야 했다. 하지만 Redux Toolkit을 사용하면 마치 상태를 직접 변경하는 것처럼 코드를 작성할 수 있음. 실제로는 Redux Toolkit 내부에서 <strong>Immer</strong>라는 라이브러리를 사용하여, 이러한 <strong>불변성을 유지하면서도 가변적인 코드처럼 보이게 해주는 기능</strong>을 제공하는 것이다. 즉, 상태를 직접 변경하는 것처럼 보여도, 실제로는 Immer가 이를 감지하여 새로운 상태를 생성해주는 것이다.</p><h4>Action -명령</h4><p>useDispatch를 불러서 명령하려는 action을 넣어준다.</p><pre>import { backeryActions } from &quot;..파일경로&quot;<br><br>const PretzelBakery = () =&gt; {<br>  // 전역적으로 관리되어 state로 바로 쓸 수 있다. <br>  const pretzels = useSelector((state) =&gt; state.bakery.pretzels);<br>  const dispatch = useDispatch();<br><br><br>  reutrn (<br>    &lt;div&gt;<br>      &lt;h1&gt;빵집&lt;/h1&gt;<br>      &lt;p&gt;남은 프레첼: {pretzels}개&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch(bakeryActions.bakePretzel())}&gt;프레첼 굽기&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch(bakeryActions.isOpen())}&gt;가게열기&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>파일 관리법</h3><p>store폴더를 만들어 reducer 에 따라 분리하여 넣음. 깃허브를 보니까 slices폴더 만들어서 따로 넣는 경우가 많았다</p><pre>src/<br>├── store/              # Redux 사용폴더 <br>│   ├── index.js       # configureStore export 하는 곳 <br>│   │<br>│   └── slices/        # createSlice 모아두는 곳 <br>│       ├── bakerySlice.js       <br>│       └── parkingLotSlice.js   <br>│<br>└── components/        <br>    └── BreadCounter.js  </pre><h3>핵심개념</h3><ol><li><strong>Redux는 전역 상태관리 시스템</strong></li></ol><ul><li>모든 컴포넌트가 공유하는 상태를 기록</li><li>상태를 바꾸려면 Reducer에 있는 규칙을 따라야함</li></ul><p><strong>2. Redux의 3대 요소</strong></p><ul><li><strong>Store </strong>— 전역 데이터 저장소</li><li><strong>Reducer </strong>— 데이터를 바꾸는 규칙</li><li><strong>Action </strong>— 무슨 행동할지 전달</li></ul><p><strong>3. React 앱 전체에서 사용할 수 있도록 최상위 컴포넌트에서 Provider로 감싸 주입한다.</strong></p><p>index.js 또는 main.jsx</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import App from &#39;./App&#39;;<br>import store from &#39;./store&#39;; // configureStore or createStore로 만든 store<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/Provider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dcf107460f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>