{"componentChunkName":"component---src-pages-markdown-remark-fields-slug-js","path":"/engineering/react-state-management/","result":{"data":{"markdownRemark":{"id":"2149e011-27d4-59d7-9f86-b39f7d80de97","excerpt":"Biggest Challenge in React application is the management of state for frontend developers. In large applications, React alone is not sufficient to handle the…","html":"<p>Biggest Challenge in React application is the management of state for frontend developers. In large applications, React alone is not sufficient to handle the complexity which is why some developers use React hooks and others use state management libraries such as Redux.</p>\n<p>In this post, We are going to take a closer look at both React hooks and Redux to manage the state.</p>\n<h2 id=\"what-is-react-state-management\" style=\"position:relative;\"><a href=\"#what-is-react-state-management\" aria-label=\"what is react state management permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is React State Management?</h2>\n<p>React components have a built-in state object. The state is encapsulated data where you store assets that are persistent between component renderings.</p>\n<p>The state is just a fancy term for a JavaScript data structure. If a user changes state by interacting with your application, the UI may look completely different afterwards, because it's represented by this new state rather than the old state.</p>\n<blockquote>\n<p><strong>Make a state variable responsible for one concern to use efficiently</strong>.</p>\n</blockquote>\n<h2 id=\"why-do-you-need-react-state-management\" style=\"position:relative;\"><a href=\"#why-do-you-need-react-state-management\" aria-label=\"why do you need react state management permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why do you need React state management?</h2>\n<p>React applications are built using components and they manage their state internally and it works well for applications with few components, but when the application grows bigger, the complexity of managing states shared across components becomes difficult.</p>\n<p>Here is a simple example of an e-commerce application, in which the status of multiple components will change when purchasing a product.</p>\n<ul>\n<li>Add that product to the shopping list</li>\n<li>Add product to customer history</li>\n<li>trigger count of purchased products</li>\n</ul>\n<p>If developers do not have scalability in mind then it is really hard to find out what is happening when something goes wrong. This is why you need state management in your application.</p>\n<p>Let’s discuss how to use react state management using react hooks and redux</p>\n<h2 id=\"what-is-redux\" style=\"position:relative;\"><a href=\"#what-is-redux\" aria-label=\"what is redux permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is Redux?</h2>\n<p>Redux was created to resolve this particular issue. it provides a central store that holds all states of your application. Each component can access the stored state without sending it from one component to another.  Here is a simple view of how Redux works.</p>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 768px; \"\n    >\n      <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 56.30769230769231%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAALCAYAAAB/Ca1DAAAACXBIWXMAAAsTAAALEwEAmpwYAAAC/UlEQVQoz01SW0hUURRdd8ZCpaIc0j6KXtiLIEJNpIf2/DCFSjMpLcKfMKUys4dIjxEjk8aZ64hOls507+iMzzF7D0ikaYpkkVhqcx+jToJ+9dFHyGnfIaIL655zWGuvs8/eG8nJyfgfBw/tBWMMs4MM9spvvGCRf7Y+UlSPXZ0Sq+QfgkWSqu/2rbeWvQfzMUStBNKOZSLlcGowHrbyj9xbF+MKcitC0o5mLk8/dspw8dy9MCxGWL1pNI8MPS11itgl+hudVbKLDB33bz5ftScpPvLokYzNx9OyloI+s7FbR5wOjdZJNJi+YsjDEBqF8OitiwzEL7QY36Lm3gAEs4oXTX70eQNoqlZAQSjKt2geOkIo8zNUlw0SNxXk6CcvE3hftGgOrOZvD23gS3s3u6oDawgLyopbOMGi6p83+vW9rwN6MtRTkP7XCENL7azBUTkWbbzqiq0q/bCJDNcStxYiL5c/MUuMnjXvcSjMaZUZEUzkpR3ajdoz/q5BkJ4L7nnJTckwV40877ZJTPMgjpFA2k2HkmabWtBYO3LLaZWKSFhIWa/4a8L9b6idn5i/0+pLFXmlWODHr5HpFdGiXCaukGroR8ODMUz0MK0uCwl6a+kwTDdG8dA4h08vGc5k5eHAwSSkHtmPppoJVGxneFDSg1HiEIIIign3itpUjAGm2290NCZcRnq2ITMje11aSm5kYkw+da5LV3KuXxcfl4iTJ3KQtC8Bl84b4W7o4wCGndtyl6TszzPknC5cdiI9O+r6hdoFzxp+69BkneIIaLXNLBcsypfWOr/cYZf9bY8VH43JHN1q1bImcHUVw9upPL5mmyK31fumqe6kUecovshuGoOjclyv1SIIZ5UvgsRuEnd1iZMdHofaToZee+V4YVzCxqhdiTGrrXd7twhmuZ00nU+FyY72erWNmtNN8WephtQPRfev2O5aBQ6ThGdOPwa6Z/DuxTRcNSoeln9GbMJ6bNoWAdOdV0ENDTn6vTPo7pzWuh6Mp2Q4ajD+ABjguSUc0CB4AAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"using react state management with redux flowchart\"\n        title=\"using react state management with redux flowchart\"\n        src=\"/static/878d2cde053633bfea88a8bfcfc28e89/e5715/image1.png\"\n        srcset=\"/static/878d2cde053633bfea88a8bfcfc28e89/a6d36/image1.png 650w,\n/static/878d2cde053633bfea88a8bfcfc28e89/e5715/image1.png 768w,\n/static/878d2cde053633bfea88a8bfcfc28e89/29007/image1.png 1600w\"\n        sizes=\"(max-width: 768px) 100vw, 768px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n      />\n    </span></p>\n<p>There are three building parts: actions, store, and reducers. Let’s briefly discuss what each of them does.</p>\n<h4 id=\"actions-in-redux\" style=\"position:relative;\"><a href=\"#actions-in-redux\" aria-label=\"actions in redux permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Actions in Redux</h4>\n<p>Actions are payloads of information that send data from your application to your store. Actions are sent using  <a href=\"https://redux.js.org/api/store#dispatchaction\"><code>store.dispatch()</code></a>. Actions are created via an action creator.\nHere is an example action that represents adding a new todo item:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"0\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">{ </span>\n<span class=\"grvsc-line\">type: &quot;ADD_TODO&quot;, </span>\n<span class=\"grvsc-line\">payload: {text:&quot;Hello Foo&quot;}</span>\n<span class=\"grvsc-line\"> }</span></code></pre>\n<p>Here is an example of its action creator:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"1\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">ocnst addTodo = (text) =&gt; {</span>\n<span class=\"grvsc-line\">  return {</span>\n<span class=\"grvsc-line\">     type: &quot;ADD_TODO&quot;,</span>\n<span class=\"grvsc-line\">     text</span>\n<span class=\"grvsc-line\">  };</span>\n<span class=\"grvsc-line\">}</span></code></pre>\n<h4 id=\"reducers-in-redux\" style=\"position:relative;\"><a href=\"#reducers-in-redux\" aria-label=\"reducers in redux permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Reducers in Redux</h4>\n<p>Reducers specify how the application's state changes in response to actions sent to the store.\nAn example of how Reducer works in Redux is as follows:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"2\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">  const TODOReducer= (state = {}, action) =&gt; {</span>\n<span class=\"grvsc-line\">  switch (action.type) {</span>\n<span class=\"grvsc-line\">    case &quot;ADD_TODO&quot;:</span>\n<span class=\"grvsc-line\">      return {</span>\n<span class=\"grvsc-line\">        ...state,</span>\n<span class=\"grvsc-line\">        ...action.payload</span>\n<span class=\"grvsc-line\">      };</span>\n<span class=\"grvsc-line\">    default:</span>\n<span class=\"grvsc-line\">      return state;</span>\n<span class=\"grvsc-line\">  }</span>\n<span class=\"grvsc-line\">};</span></code></pre>\n<h4 id=\"store-in-redux\" style=\"position:relative;\"><a href=\"#store-in-redux\" aria-label=\"store in redux permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Store in Redux</h4>\n<p>The store holds the application state. You can access stored state, update the state, and register or unregister listeners via helper methods.</p>\n<p>Let’s create a store for our TODO app:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"3\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">const store = createStore(TODOReducer);</span></code></pre>\n<p>In other words, Redux gives you code organization and debugging superpowers. This makes it easier to build more maintainable code, and much easier to track down the root cause when something goes wrong.</p>\n<h2 id=\"what-is-react-hook\" style=\"position:relative;\"><a href=\"#what-is-react-hook\" aria-label=\"what is react hook permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is React Hook?</h2>\n<p>These are functions that hook you into React state and features from function components. Hooks don't work inside classes  and it allows you to use React features without writing a class. </p>\n<p>Hooks are backwards-compatible, which means it doesn't keep any breaking changes. <a href=\"/react-hooks-guide/\">React provides some built-in Hooks</a> like <code>useState</code>, <code>UseEffect</code> and <code>useReducer</code> etc. You can also make custom hooks.</p>\n<h3 id=\"react-hook-rules\" style=\"position:relative;\"><a href=\"#react-hook-rules\" aria-label=\"react hook rules permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>React Hook Rules</h3>\n<ul>\n<li>Call hook at the top level only means that you need to call inside a loop, nested function, or conditions.</li>\n<li>React function components are called hooks only.</li>\n</ul>\n<p>Please see the following examples of some react hooks as follows:</p>\n<h5 id=\"what-is-usestate-and-how-to--use-it\" style=\"position:relative;\"><a href=\"#what-is-usestate-and-how-to--use-it\" aria-label=\"what is usestate and how to  use it permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What is useState and how to  use it</h5>\n<p><code>useState</code> is a Hook that Lets you add React state to function components.\nExample:\nDeclaring a State Variable in class and initialize count state with 0 by setting this.state  to {count:0}.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"4\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">class Example extends React.Component {</span>\n<span class=\"grvsc-line\">  constructor(props) {</span>\n<span class=\"grvsc-line\">    super(props);</span>\n<span class=\"grvsc-line\">    this.state = {</span>\n<span class=\"grvsc-line\">      count: 0</span>\n<span class=\"grvsc-line\">    };</span>\n<span class=\"grvsc-line\">  }</span>\n<span class=\"grvsc-line\">  </span></code></pre>\n<p>In a function component, we have no this, so we can’t assign or read this.state. Instead, we call the <code>useState</code> Hook directly inside our component:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"5\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">function Example() {</span>\n<span class=\"grvsc-line\">    const [count, setCount] = useState(0);</span>\n<span class=\"grvsc-line\">}</span></code></pre>\n<p>We declare a state variable called count and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.</p>\n<h5 id=\"what-is-usereducer-and-how-to-use-it\" style=\"position:relative;\"><a href=\"#what-is-usereducer-and-how-to-use-it\" aria-label=\"what is usereducer and how to use it permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>what is useReducer and how to use it</h5>\n<p><code>useReducer</code> is a hook I use sometimes to manage the state of the application. It is very similar to the <em>useState</em> hook, just more complex. <em>useReducer</em> hook uses the same concept as the reducers in Redux. It is basically a pure function, with no side-effects.</p>\n<p>Example of useReducer:</p>\n<p>useReducer creates an independent component co-located state container within your component. Whereas Redux creates a global state container that hangs somewhere above your entire application.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"6\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">          +----------------+              +----------------+</span>\n<span class=\"grvsc-line\">          |  Component A   |              |                |</span>\n<span class=\"grvsc-line\">          |                |              |                |</span>\n<span class=\"grvsc-line\">          |                |              |      Redux     |</span>\n<span class=\"grvsc-line\">          +----------------+              |                |</span>\n<span class=\"grvsc-line\">          | connect Redux  |&lt;-------------|                |</span>\n<span class=\"grvsc-line\">          +--------+-------+              +--------+-------+</span>\n<span class=\"grvsc-line\">                   |                               |</span>\n<span class=\"grvsc-line\">         +---------+-----------+                   |</span>\n<span class=\"grvsc-line\">         |                     |                   |</span>\n<span class=\"grvsc-line\">         |                     |                   |</span>\n<span class=\"grvsc-line\">+--------+-------+    +--------+-------+           |</span>\n<span class=\"grvsc-line\">|  Component B   |    |  Component C   |           |</span>\n<span class=\"grvsc-line\">|                |    |                |           |</span>\n<span class=\"grvsc-line\">|                |    |                |           |</span>\n<span class=\"grvsc-line\">+----------------+    +----------------+           |</span>\n<span class=\"grvsc-line\">|    useReducer  |    | connect Redux  |&lt;----------+</span>\n<span class=\"grvsc-line\">+----------------+    +--------+-------+</span>\n<span class=\"grvsc-line\">                               |</span>\n<span class=\"grvsc-line\">                      +--------+-------+</span>\n<span class=\"grvsc-line\">                      |  Component D   |</span>\n<span class=\"grvsc-line\">                      |                |</span>\n<span class=\"grvsc-line\">                      |                |</span>\n<span class=\"grvsc-line\">                      +----------------+</span></code></pre>\n<p>Below an example of todo items is completed or not using the useReducer react hook.</p>\n<p>See the following function which  is a reducer function for managing state transitions for a list of items:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"7\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"> const todoReducer = (state, action) =&gt; {</span>\n<span class=\"grvsc-line\">      switch (action.type) {</span>\n<span class=\"grvsc-line\">        case &quot;ADD_TODO&quot;:</span>\n<span class=\"grvsc-line\">          return state.map(todo =&gt; {</span>\n<span class=\"grvsc-line\">            if (todo.id === action.id) {</span>\n<span class=\"grvsc-line\">              return { ...todo, complete: true };</span>\n<span class=\"grvsc-line\">            } else {</span>\n<span class=\"grvsc-line\">              return todo;</span>\n<span class=\"grvsc-line\">            }</span>\n<span class=\"grvsc-line\">          });</span>\n<span class=\"grvsc-line\">        case &quot;REMOVE_TODO&quot;:</span>\n<span class=\"grvsc-line\">          return state.map(todo =&gt; {</span>\n<span class=\"grvsc-line\">            if (todo.id === action.id) {</span>\n<span class=\"grvsc-line\">              return { ...todo, complete: false };</span>\n<span class=\"grvsc-line\">            } else {</span>\n<span class=\"grvsc-line\">              return todo;</span>\n<span class=\"grvsc-line\">            }</span>\n<span class=\"grvsc-line\">          });</span>\n<span class=\"grvsc-line\">        default:</span>\n<span class=\"grvsc-line\">          return state;</span>\n<span class=\"grvsc-line\">      }</span>\n<span class=\"grvsc-line\">    };</span></code></pre>\n<p>There are two types of actions which are equivalent to two states. they used to toggle the complete boolean field and additional payload to identify incoming action.</p>\n<p>The state which is managed in this reducer is an array of items:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"8\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">const initialTodos = [</span>\n<span class=\"grvsc-line\">      {</span>\n<span class=\"grvsc-line\">        id: &quot;t1&quot;,</span>\n<span class=\"grvsc-line\">        task: &quot;Add Task 1&quot;,</span>\n<span class=\"grvsc-line\">        complete: false</span>\n<span class=\"grvsc-line\">      },</span>\n<span class=\"grvsc-line\">      {</span>\n<span class=\"grvsc-line\">        id: &quot;t2&quot;,</span>\n<span class=\"grvsc-line\">        task: &quot;Add Task 2&quot;,</span>\n<span class=\"grvsc-line\">        complete: false</span>\n<span class=\"grvsc-line\">      }</span>\n<span class=\"grvsc-line\">    ];</span></code></pre>\n<p>In code, The useReducer hook is used for complex state and state transitions. It takes a reducer function and an initial state as input and returns the current state and a dispatch function as output</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"9\"><code class=\"grvsc-code\"><span class=\"grvsc-line\"> const [todos, dispatch] = React.useReducer(</span>\n<span class=\"grvsc-line\">    todoReducer,</span>\n<span class=\"grvsc-line\">    initialTodos</span>\n<span class=\"grvsc-line\">  );</span></code></pre>\n<p>Complete file:</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"10\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">import React from &quot;react&quot;;</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">const initialTodos = [</span>\n<span class=\"grvsc-line\">  {</span>\n<span class=\"grvsc-line\">    id: &quot;t1&quot;,</span>\n<span class=\"grvsc-line\">    task: &quot;Add Task 1&quot;,</span>\n<span class=\"grvsc-line\">    complete: false</span>\n<span class=\"grvsc-line\">  },</span>\n<span class=\"grvsc-line\">  {</span>\n<span class=\"grvsc-line\">    id: &quot;t2&quot;,</span>\n<span class=\"grvsc-line\">    task: &quot;Add Task 2&quot;,</span>\n<span class=\"grvsc-line\">    complete: false</span>\n<span class=\"grvsc-line\">  }</span>\n<span class=\"grvsc-line\">];</span>\n<span class=\"grvsc-line\">const todoReducer = (state, action) =&gt; {</span>\n<span class=\"grvsc-line\">  switch (action.type) {</span>\n<span class=\"grvsc-line\">    case &quot;ADD_TODO&quot;:</span>\n<span class=\"grvsc-line\">      return state.map(todo =&gt; {</span>\n<span class=\"grvsc-line\">        if (todo.id === action.id) {</span>\n<span class=\"grvsc-line\">          return { ...todo, complete: true };</span>\n<span class=\"grvsc-line\">        } else {</span>\n<span class=\"grvsc-line\">          return todo;</span>\n<span class=\"grvsc-line\">        }</span>\n<span class=\"grvsc-line\">      });</span>\n<span class=\"grvsc-line\">    case &quot;REMOVE_TODO&quot;:</span>\n<span class=\"grvsc-line\">      return state.map(todo =&gt; {</span>\n<span class=\"grvsc-line\">        if (todo.id === action.id) {</span>\n<span class=\"grvsc-line\">          return { ...todo, complete: false };</span>\n<span class=\"grvsc-line\">        } else {</span>\n<span class=\"grvsc-line\">          return todo;</span>\n<span class=\"grvsc-line\">        }</span>\n<span class=\"grvsc-line\">      });</span>\n<span class=\"grvsc-line\">    default:</span>\n<span class=\"grvsc-line\">      return state;</span>\n<span class=\"grvsc-line\">  }</span>\n<span class=\"grvsc-line\">};</span>\n<span class=\"grvsc-line\">const App = () =&gt; {</span>\n<span class=\"grvsc-line\">  const [todos, dispatch] = React.useReducer(todoReducer, initialTodos);</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">  const handleChange = todo =&gt; {</span>\n<span class=\"grvsc-line\">    dispatch({</span>\n<span class=\"grvsc-line\">      type: todo.complete ? &quot;REMOVE_TODO&quot; : &quot;ADD_TODO&quot;,</span>\n<span class=\"grvsc-line\">      id: todo.id</span>\n<span class=\"grvsc-line\">    });</span>\n<span class=\"grvsc-line\">  };</span>\n<span class=\"grvsc-line\">  return (</span>\n<span class=\"grvsc-line\">    &lt;ul&gt;</span>\n<span class=\"grvsc-line\">      {todos.map(todo =&gt; (</span>\n<span class=\"grvsc-line\">        &lt;li key={todo.id}&gt;</span>\n<span class=\"grvsc-line\">          &lt;label&gt;</span>\n<span class=\"grvsc-line\">            &lt;input</span>\n<span class=\"grvsc-line\">              type=&quot;checkbox&quot;</span>\n<span class=\"grvsc-line\">              checked={todo.complete}</span>\n<span class=\"grvsc-line\">              onChange={() =&gt; handleChange(todo)}</span>\n<span class=\"grvsc-line\">            /&gt;</span>\n<span class=\"grvsc-line\">            {todo.task}</span>\n<span class=\"grvsc-line\">          &lt;/label&gt;</span>\n<span class=\"grvsc-line\">        &lt;/li&gt;</span>\n<span class=\"grvsc-line\">      ))}</span>\n<span class=\"grvsc-line\">    &lt;/ul&gt;</span>\n<span class=\"grvsc-line\">  );</span>\n<span class=\"grvsc-line\">};</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">export default App;</span></code></pre>\n<p>Let’s do a similar example with Redux.</p>\n<p>Store in <em>App.js</em>.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"11\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">import React from &quot;react&quot;;</span>\n<span class=\"grvsc-line\">import { Provider } from &quot;react-redux&quot;;</span>\n<span class=\"grvsc-line\">import { createStore } from &quot;redux&quot;;</span>\n<span class=\"grvsc-line\">import rootReducer from &quot;./reducers&quot;;</span>\n<span class=\"grvsc-line\">import Todo from &quot;./Components/TODO&quot;;</span>\n<span class=\"grvsc-line\">const store = createStore(rootReducer);</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">function App() {</span>\n<span class=\"grvsc-line\">  return (</span>\n<span class=\"grvsc-line\">    &lt;div className=&quot;App&quot;&gt;</span>\n<span class=\"grvsc-line\">      &lt;Provider store={store}&gt;</span>\n<span class=\"grvsc-line\">        &lt;Todo /&gt;</span>\n<span class=\"grvsc-line\">      &lt;/Provider&gt;</span>\n<span class=\"grvsc-line\">    &lt;/div&gt;</span>\n<span class=\"grvsc-line\">  );</span>\n<span class=\"grvsc-line\">}</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">export default App;</span></code></pre>\n<p>Actions in <em>actions/index.js</em>.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"12\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">export const addTodo = id =&gt; ({</span>\n<span class=\"grvsc-line\">  type: &quot;ADD_TODO&quot;,</span>\n<span class=\"grvsc-line\">  id</span>\n<span class=\"grvsc-line\">});</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">export const removeTodo = id =&gt; ({</span>\n<span class=\"grvsc-line\">  type: &quot;REMOVE_TODO&quot;,</span>\n<span class=\"grvsc-line\">  id</span>\n<span class=\"grvsc-line\">});</span></code></pre>\n<p>Reducers in <em>reducers/index.js</em>.</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"13\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">const initialTodos = [</span>\n<span class=\"grvsc-line\">  {</span>\n<span class=\"grvsc-line\">    id: &quot;t1&quot;,</span>\n<span class=\"grvsc-line\">    task: &quot;Add Task 1&quot;,</span>\n<span class=\"grvsc-line\">    complete: false</span>\n<span class=\"grvsc-line\">  },</span>\n<span class=\"grvsc-line\">  {</span>\n<span class=\"grvsc-line\">    id: &quot;t2&quot;,</span>\n<span class=\"grvsc-line\">    task: &quot;Add Task 2&quot;,</span>\n<span class=\"grvsc-line\">    complete: false</span>\n<span class=\"grvsc-line\">  }</span>\n<span class=\"grvsc-line\">];</span>\n<span class=\"grvsc-line\">const todos = (state = initialTodos, action) =&gt; {</span>\n<span class=\"grvsc-line\">  switch (action.type) {</span>\n<span class=\"grvsc-line\">    case &quot;ADD_TODO&quot;:</span>\n<span class=\"grvsc-line\">      return state.map(todo =&gt; {</span>\n<span class=\"grvsc-line\">        if (todo.id === action.id) {</span>\n<span class=\"grvsc-line\">          return { ...todo, complete: true };</span>\n<span class=\"grvsc-line\">        } else {</span>\n<span class=\"grvsc-line\">          return todo;</span>\n<span class=\"grvsc-line\">        }</span>\n<span class=\"grvsc-line\">      });</span>\n<span class=\"grvsc-line\">    case &quot;REMOVE_TODO&quot;:</span>\n<span class=\"grvsc-line\">      return state.map(todo =&gt; {</span>\n<span class=\"grvsc-line\">        if (todo.id === action.id) {</span>\n<span class=\"grvsc-line\">          return { ...todo, complete: false };</span>\n<span class=\"grvsc-line\">        } else {</span>\n<span class=\"grvsc-line\">          return todo;</span>\n<span class=\"grvsc-line\">        }</span>\n<span class=\"grvsc-line\">      });</span>\n<span class=\"grvsc-line\">    default:</span>\n<span class=\"grvsc-line\">      return state;</span>\n<span class=\"grvsc-line\">  }</span>\n<span class=\"grvsc-line\">};</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">export default todos;</span></code></pre>\n<p>FIle components/Todo.js</p>\n<pre class=\"grvsc-container dark-default-dark\" data-language=\"\" data-index=\"14\"><code class=\"grvsc-code\"><span class=\"grvsc-line\">import React from &quot;react&quot;;</span>\n<span class=\"grvsc-line\">import { connect } from &quot;react-redux&quot;;</span>\n<span class=\"grvsc-line\">import { addTodo, removeTodo } from &quot;../../redux/actions/authActions&quot;;</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">const Todo = ({ todos, addTodo, removeTodo }) =&gt; {</span>\n<span class=\"grvsc-line\">  const handleChange = todo =&gt; {</span>\n<span class=\"grvsc-line\">    if (todo.complete) {</span>\n<span class=\"grvsc-line\">      removeTodo(todo.id);</span>\n<span class=\"grvsc-line\">    } else {</span>\n<span class=\"grvsc-line\">      addTodo(todo.id);</span>\n<span class=\"grvsc-line\">    }</span>\n<span class=\"grvsc-line\">  };</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">  return (</span>\n<span class=\"grvsc-line\">    &lt;ul&gt;</span>\n<span class=\"grvsc-line\">      {todos.map(todo =&gt; (</span>\n<span class=\"grvsc-line\">        &lt;li key={todo.id}&gt;</span>\n<span class=\"grvsc-line\">          &lt;label&gt;</span>\n<span class=\"grvsc-line\">            &lt;input</span>\n<span class=\"grvsc-line\">              type=&quot;checkbox&quot;</span>\n<span class=\"grvsc-line\">              checked={todo.complete}</span>\n<span class=\"grvsc-line\">              onChange={() =&gt; handleChange(todo)}</span>\n<span class=\"grvsc-line\">            /&gt;</span>\n<span class=\"grvsc-line\">            {todo.task}</span>\n<span class=\"grvsc-line\">          &lt;/label&gt;</span>\n<span class=\"grvsc-line\">        &lt;/li&gt;</span>\n<span class=\"grvsc-line\">      ))}</span>\n<span class=\"grvsc-line\">    &lt;/ul&gt;</span>\n<span class=\"grvsc-line\">  );</span>\n<span class=\"grvsc-line\">};</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">const mapStateToProps = state =&gt; ({ todos: state.auth.todos });</span>\n<span class=\"grvsc-line\">const mapDispatchToProps = dispatch =&gt; {</span>\n<span class=\"grvsc-line\">  return {</span>\n<span class=\"grvsc-line\">    addTodo: id =&gt; dispatch(addTodo(id)),</span>\n<span class=\"grvsc-line\">    removeTodo: id =&gt; dispatch(removeTodo(id))</span>\n<span class=\"grvsc-line\">  };</span>\n<span class=\"grvsc-line\">};</span>\n<span class=\"grvsc-line\"></span>\n<span class=\"grvsc-line\">export default connect(</span>\n<span class=\"grvsc-line\">  mapStateToProps,</span>\n<span class=\"grvsc-line\">  mapDispatchToProps</span>\n<span class=\"grvsc-line\">)(Todo);</span></code></pre>\n<p>React offers react hooks which can be used as an alternative for <code>connect()</code>. You can use built-in hooks mainly useState, UseReducer and useContext and because of these you often may not require Redux. </p>\n<p>But for large applications, you can use both redux and react hooks. it works great! React Hook is a useful new feature, and the addition of React-Redux with Redux-specific hooks is a great step towards simplifying Redux development.</p>\n<style class=\"grvsc-styles\">\n  .grvsc-container {\n    overflow: auto;\n    -webkit-overflow-scrolling: touch;\n    padding-top: 1rem;\n    padding-top: var(--grvsc-padding-top, var(--grvsc-padding-v, 1rem));\n    padding-bottom: 1rem;\n    padding-bottom: var(--grvsc-padding-bottom, var(--grvsc-padding-v, 1rem));\n    border-radius: 8px;\n    border-radius: var(--grvsc-border-radius, 8px);\n    font-feature-settings: normal;\n  }\n  \n  .grvsc-code {\n    display: inline-block;\n    min-width: 100%;\n  }\n  \n  .grvsc-line {\n    display: inline-block;\n    box-sizing: border-box;\n    width: 100%;\n    padding-left: 1.5rem;\n    padding-left: var(--grvsc-padding-left, var(--grvsc-padding-h, 1.5rem));\n    padding-right: 1.5rem;\n    padding-right: var(--grvsc-padding-right, var(--grvsc-padding-h, 1.5rem));\n  }\n  \n  .grvsc-line-highlighted {\n    background-color: var(--grvsc-line-highlighted-background-color, transparent);\n    box-shadow: inset var(--grvsc-line-highlighted-border-width, 4px) 0 0 0 var(--grvsc-line-highlighted-border-color, transparent);\n  }\n  \n  .dark-default-dark {\n    background-color: #1E1E1E;\n    color: #D4D4D4;\n  }\n</style>","headings":[{"value":"What is React State Management?","depth":2},{"value":"Why do you need React state management?","depth":2},{"value":"What is Redux?","depth":2},{"value":"Actions in Redux","depth":4},{"value":"Reducers in Redux","depth":4},{"value":"Store in Redux","depth":4},{"value":"What is React Hook?","depth":2},{"value":"React Hook Rules","depth":3},{"value":"What is useState and how to  use it","depth":5},{"value":"what is useReducer and how to use it","depth":5}],"fields":{"slug":"/engineering/react-state-management/"},"frontmatter":{"metatitle":null,"metadescription":null,"description":"Learn about React state management and why we need state management and how to use it with React hooks and Redux in the best possible way.","title":"React state management: What is it and why to use it?","canonical":null,"date":"July 17, 2020","updated_date":null,"tags":["React","Redux","Hooks"],"coverImage":{"childImageSharp":{"fluid":{"aspectRatio":1.5037593984962405,"src":"/static/ef27359624480604211f0e018dd47f18/d9e4b/title-image.png","srcSet":"/static/ef27359624480604211f0e018dd47f18/f5f11/title-image.png 200w,\n/static/ef27359624480604211f0e018dd47f18/6d133/title-image.png 400w,\n/static/ef27359624480604211f0e018dd47f18/d9e4b/title-image.png 512w","sizes":"(max-width: 512px) 100vw, 512px"}}},"author":{"id":"Versha Gupta","github":"vershagupta","bio":"She is a software enthusiast, an avid contributor, and a regular blog writer. She usually works with React, UI/UX, Javascript, Node.js, and DevOps.","avatar":null}}}},"pageContext":{"id":"2149e011-27d4-59d7-9f86-b39f7d80de97","fields__slug":"/engineering/react-state-management/","__params":{"fields__slug":"engineering"}}},"staticQueryHashes":["1171199041","1384082988","1711371485","1753898100","2100481360","229320306","23180105","528864852"]}