{"id":32845,"date":"2024-11-01T09:11:57","date_gmt":"2024-11-01T09:11:57","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=32845"},"modified":"2024-11-01T11:21:45","modified_gmt":"2024-11-01T11:21:45","slug":"react-course-understanding-usereducer","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/32845\/","title":{"rendered":"React Course: Understanding useReducer"},"content":{"rendered":"<p>\n  React is a component-based JavaScript library widely used for building user interfaces (UI). The two main state management hooks in React are useState and useReducer. In this tutorial, we will take a deep dive into useReducer.\n<\/p>\n<h2>1. What is useReducer?<\/h2>\n<p>\n  useReducer is one of React&#8217;s built-in hooks used to manage complex state logic. This hook updates the state by calling a specific function whenever there is a state change. While useState is suitable for simple state management, useReducer is better suited for more complex logic or when multiple state changes are needed.\n<\/p>\n<h2>2. Basic Usage of useReducer<\/h2>\n<p>The basic way to use useReducer is as follows.<\/p>\n<pre>\n<code>\nimport React, { useReducer } from 'react';\n\nconst initialState = { count: 0 };\n\nfunction reducer(state, action) {\n  switch (action.type) {\n    case 'increment':\n      return { count: state.count + 1 };\n    case 'decrement':\n      return { count: state.count - 1 };\n    default:\n      throw new Error();\n  }\n}\n\nfunction Counter() {\n  const [state, dispatch] = useReducer(reducer, initialState);\n\n  return (\n    &lt;div&gt;\n      &lt;p&gt;Count: {state.count}&lt;\/p&gt;\n      &lt;button onClick={() =&gt; dispatch({ type: 'increment' })}&gt;Increment&lt;\/button&gt;\n      &lt;button onClick={() =&gt; dispatch({ type: 'decrement' })}&gt;Decrement&lt;\/button&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/code>\n<\/pre>\n<p>\n  As seen in the example above, useReducer uses two arguments:<br \/>\n  <strong>the reducer function<\/strong> and <strong>the initial state<\/strong>. The reducer function takes the current state and action as parameters and returns the new state. The dispatch function updates the state using the action object.\n<\/p>\n<h2>3. Advantages of useReducer<\/h2>\n<ul>\n<li>\n<strong>Complex state management:<\/strong> useReducer is a powerful tool for managing multiple states. It allows for clear delineation of various actions and states.\n  <\/li>\n<li>\n<strong>Refactoring and scalability:<\/strong> Because the reducer function is maintained independently, it makes refactoring state logic easier.\n  <\/li>\n<li>\n<strong>Testability:<\/strong> The reducer function is a pure function, making it relatively easy to unit test.\n  <\/li>\n<\/ul>\n<h2>4. Comparison of useReducer and useState<\/h2>\n<p>\n  While both useState and useReducer help manage states, each is suited for different situations based on its usage.\n<\/p>\n<table border=\"1\">\n<thead>\n<tr>\n<th>Feature<\/th>\n<th>useState<\/th>\n<th>useReducer<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Simple state<\/td>\n<td>Advantageous<\/td>\n<td>Disadvantageous<\/td>\n<\/tr>\n<tr>\n<td>Complex state<\/td>\n<td>Disadvantageous<\/td>\n<td>Advantageous<\/td>\n<\/tr>\n<tr>\n<td>State change logic<\/td>\n<td>Disadvantageous<\/td>\n<td>Advantageous<\/td>\n<\/tr>\n<tr>\n<td>Separation of states<\/td>\n<td>Disadvantageous<\/td>\n<td>Advantageous<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>5. Practical Example: Creating a ToDo List App<\/h2>\n<p>\n  Now we will create a simple ToDo list app using useReducer. This app will include features to add and remove tasks.\n<\/p>\n<pre>\n<code>\nimport React, { useReducer } from 'react';\n\nconst initialState = { todos: [] };\n\nfunction reducer(state, action) {\n  switch (action.type) {\n    case 'add':\n      return { ...state, todos: [...state.todos, action.payload] };\n    case 'remove':\n      return { ...state, todos: state.todos.filter((_, index) =&gt; index !== action.payload) };\n    default:\n      throw new Error();\n  }\n}\n\nfunction TodoApp() {\n  const [state, dispatch] = useReducer(reducer, initialState);\n  const [input, setInput] = React.useState('');\n\n  const addTodo = () =&gt; {\n    dispatch({ type: 'add', payload: input });\n    setInput('');\n  };\n\n  return (\n    &lt;div&gt;\n      &lt;h2&gt;ToDo List&lt;\/h2&gt;\n      &lt;input \n        type=\"text\" \n        value={input} \n        onChange={(e) =&gt; setInput(e.target.value)} \n      \/&gt;\n      &lt;button onClick={addTodo}&gt;Add&lt;\/button&gt;\n      &lt;ul&gt;\n        {state.todos.map((todo, index) =&gt; (\n          &lt;li key={index}&gt;\n            {todo} &lt;button onClick={() =&gt; dispatch({ type: 'remove', payload: index })}&gt;Remove&lt;\/button&gt;\n          &lt;\/li&gt;\n        ))}\n      &lt;\/ul&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/code>\n<\/pre>\n<p>\n  The above TodoApp component provides functionality for users to add and remove tasks. It manages state using useReducer, defining logic to add or delete tasks based on each action (type).\n<\/p>\n<h2>6. Advanced Usage of useReducer<\/h2>\n<p>\n  Beyond simple state management, useReducer supports advanced features. Here are some of them:\n<\/p>\n<h3>6.1 Loading Initial State<\/h3>\n<p>\n  This is a way to load initial state asynchronously. To do this, we use the useEffect hook.\n<\/p>\n<pre>\n<code>\nimport React, { useReducer, useEffect } from 'react';\n\nfunction App() {\n  const [state, dispatch] = useReducer(reducer, initialState);\n\n  useEffect(() =&gt; {\n    const fetchData = async () =&gt; {\n      const response = await fetch('\/api\/todos');\n      const data = await response.json();\n      data.forEach(todo =&gt; dispatch({ type: 'add', payload: todo }));\n    };\n    fetchData();\n  }, []);\n\n  \/\/ Remaining app code...\n}\n<\/code>\n<\/pre>\n<h3>6.2 Nested State Management<\/h3>\n<p>\n  You can implement structured state management by combining multiple reducers. When used with the context API, global state management can be handled easily.\n<\/p>\n<pre>\n<code>\nfunction mainReducer(state, action) {\n  return {\n    counter: counterReducer(state.counter, action),\n    todos: todoReducer(state.todos, action),\n  };\n}\n\n\/\/ State and dispatch are provided with multiple reducers.\nconst [state, dispatch] = useReducer(mainReducer, initialState);\n<\/code>\n<\/pre>\n<h2>7. Conclusion<\/h2>\n<p>\n  useReducer is a powerful tool for building complex state management logic in React. Especially when multiple state changes are necessary, useReducer can enhance the readability and maintainability of your code. Based on what we learned in this tutorial, try utilizing useReducer in your own React applications.\n<\/p>\n<p>\n  If you have additional examples you want to practice or questions, please leave a comment. We support your journey in React development!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>React is a component-based JavaScript library widely used for building user interfaces (UI). The two main state management hooks in React are useState and useReducer. In this tutorial, we will take a deep dive into useReducer. 1. What is useReducer? useReducer is one of React&#8217;s built-in hooks used to manage complex state logic. This hook &hellip; <a href=\"https:\/\/atmokpo.com\/w\/32845\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;React Course: Understanding useReducer&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[123],"tags":[],"class_list":["post-32845","post","type-post","status-publish","format-standard","hentry","category-react-basics-course"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>React Course: Understanding useReducer - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/32845\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"React Course: Understanding useReducer - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"React is a component-based JavaScript library widely used for building user interfaces (UI). The two main state management hooks in React are useState and useReducer. In this tutorial, we will take a deep dive into useReducer. 1. What is useReducer? useReducer is one of React&#8217;s built-in hooks used to manage complex state logic. This hook &hellip; \ub354 \ubcf4\uae30 &quot;React Course: Understanding useReducer&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/32845\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:11:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:21:45+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/32845\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/32845\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"React Course: Understanding useReducer\",\"datePublished\":\"2024-11-01T09:11:57+00:00\",\"dateModified\":\"2024-11-01T11:21:45+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/32845\/\"},\"wordCount\":442,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"React basics course\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/32845\/\",\"url\":\"https:\/\/atmokpo.com\/w\/32845\/\",\"name\":\"React Course: Understanding useReducer - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:11:57+00:00\",\"dateModified\":\"2024-11-01T11:21:45+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/32845\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/32845\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/32845\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"React Course: Understanding useReducer\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"React Course: Understanding useReducer - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/32845\/","og_locale":"ko_KR","og_type":"article","og_title":"React Course: Understanding useReducer - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"React is a component-based JavaScript library widely used for building user interfaces (UI). The two main state management hooks in React are useState and useReducer. In this tutorial, we will take a deep dive into useReducer. 1. What is useReducer? useReducer is one of React&#8217;s built-in hooks used to manage complex state logic. This hook &hellip; \ub354 \ubcf4\uae30 \"React Course: Understanding useReducer\"","og_url":"https:\/\/atmokpo.com\/w\/32845\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:11:57+00:00","article_modified_time":"2024-11-01T11:21:45+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/32845\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/32845\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"React Course: Understanding useReducer","datePublished":"2024-11-01T09:11:57+00:00","dateModified":"2024-11-01T11:21:45+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/32845\/"},"wordCount":442,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["React basics course"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/32845\/","url":"https:\/\/atmokpo.com\/w\/32845\/","name":"React Course: Understanding useReducer - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:11:57+00:00","dateModified":"2024-11-01T11:21:45+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/32845\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/32845\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/32845\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"React Course: Understanding useReducer"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/32845","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=32845"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/32845\/revisions"}],"predecessor-version":[{"id":32846,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/32845\/revisions\/32846"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=32845"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=32845"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=32845"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}