{
    "componentChunkName": "component---src-pages-blog-markdown-remark-fields-slug-js",
    "path": "/blog/why-is-redux-state-immutable",
    "result": {"data":{"markdownRemark":{"html":"<p>For redux to work correctly, the state must be immutable. This means that whenever we update the redux state, we have to create a copy of the whole state and set values to fields we want to change. In code, this usually looks like:</p>\n<img style=\"width: 100%;\" src=\"/static/blog/7960175340257c733ea92577c17eaa2d/carbon-5.svg\" alt=\"code example\">\n<p>In the code above, we are modifying the oldState’s <code class=\"language-text\">field2</code> value by creating a new state and setting a new value to <code class=\"language-text\">field2</code>. The value and reference of <code class=\"language-text\">oldState</code> remains the same.</p>\n<p>Before we get into why we must change redux state in this way, we should know the difference between “value” and “reference”</p>\n<h2 id=\"difference-between-value-and-reference\" style=\"position:relative;\"><a href=\"#difference-between-value-and-reference\" aria-label=\"difference between value and reference 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>Difference between value and reference</h2>\n<p>The value of a variable is the “semantic” meaning of what that variable holds. For example, in the example code below, the semantics of what is held by <code class=\"language-text\">var1</code> and <code class=\"language-text\">var2</code> are the same, therefore we can say that their values are the same. However, <code class=\"language-text\">var3</code>’s value is different since the “semantics” of what it’s holding is different.</p>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/3d4843524ce391e7135e4883d2604111/5a190/carbon-p-800.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 24.050632911392405%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAFCAYAAABFA8wzAAAACXBIWXMAAAsSAAALEgHS3X78AAAAq0lEQVQY042P0QrCMAxF9wlil6Zpk9V2G+qr+P+f1ivdQEFUfDhc8pCbk+F+MxyUm3OMI3m4sUNw5Lf5SAzX8WHL0YcPcHO053C+lkanAokJpjOCZnBZIDFD4wSTtC99LeuHXqWD1YpwWlsyQ50uiHlGWK+waUHVGSUpRpYfdm+GmnPzU4EkhaWKYAWcK1IqMFGIxO3dvw2JpRs04gDPcbMZOYI6XkDPpf8MH/Jff9xejH7aAAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"code example\"\n        title=\"code example\"\n        src=\"/static/3d4843524ce391e7135e4883d2604111/f058b/carbon-p-800.png\"\n        srcset=\"/static/3d4843524ce391e7135e4883d2604111/c26ae/carbon-p-800.png 158w,\n/static/3d4843524ce391e7135e4883d2604111/6bdcf/carbon-p-800.png 315w,\n/static/3d4843524ce391e7135e4883d2604111/f058b/carbon-p-800.png 630w,\n/static/3d4843524ce391e7135e4883d2604111/5a190/carbon-p-800.png 800w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<p>When we talk about reference, we are referring (pun intended!) to the memory address of where something is stored. So in the above example, the memory address of the object referenced by <code class=\"language-text\">var1</code>, is different from the memory address of the object referenced by <code class=\"language-text\">var2</code>. In other words, <code class=\"language-text\">var1</code> points to a different memory address than <code class=\"language-text\">var2</code>. Therefore, their references are different, even though their values are the same!</p>\n<p>The only way two variables can have the same reference is when they are both pointing to the same memory address. So in the code below, <code class=\"language-text\">var4</code> and <code class=\"language-text\">var5</code> have the same reference:</p>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/3716ccc86f75f3538361bf6024451f9d/b5a09/carbon-1.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 16.455696202531648%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAADCAYAAACTWi8uAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAg0lEQVQI133OOw7DMAwD0ByhQGzJsuV/MxVZev+rxSziLEFRdCAoLg9a9qjH/g54MA1jCSsRzjbWwtC1V2JYYhh2MOfN7jvD0Oxj6Tng+dqGqw2aCmLscKlC2gavBSlkpBAmZn9juDCe6KJRhrYOKXX43CCaYZ2AvIKcB8/IX/D24fgAaLZNNhrWyZ8AAAAASUVORK5CYII='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"code example\"\n        title=\"code example\"\n        src=\"/static/3716ccc86f75f3538361bf6024451f9d/f058b/carbon-1.png\"\n        srcset=\"/static/3716ccc86f75f3538361bf6024451f9d/c26ae/carbon-1.png 158w,\n/static/3716ccc86f75f3538361bf6024451f9d/6bdcf/carbon-1.png 315w,\n/static/3716ccc86f75f3538361bf6024451f9d/f058b/carbon-1.png 630w,\n/static/3716ccc86f75f3538361bf6024451f9d/40601/carbon-1.png 945w,\n/static/3716ccc86f75f3538361bf6024451f9d/78612/carbon-1.png 1260w,\n/static/3716ccc86f75f3538361bf6024451f9d/b5a09/carbon-1.png 1360w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<p>If we do <code class=\"language-text\">var5.name = “Mary”</code>, then the value of <code class=\"language-text\">var4.name</code> will also be “Mary”.</p>\n<p>Based on this understanding, we can conclude:</p>\n<ul>\n<li>If the value of two variables are the same, their reference may or may not be the same.</li>\n<li>If the values of two variables are different, then their references must be different.</li>\n<li>If the reference of two variables are the same, their values must be the same.</li>\n<li>If the reference of two variables are different, their values may or may not be the same.</li>\n</ul>\n<h3 id=\"re-rendering-of-react-components\" style=\"position:relative;\"><a href=\"#re-rendering-of-react-components\" aria-label=\"re rendering of react components 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>Re rendering of react components</h3>\n<p>Coming back to redux and react, react will only want to re render a component if the value of the props or state has changed. To know if a value of these have changed, we must do a “deep comparison” - recursively check all the fields inside the state and prop to see if any of them have changed.</p>\n<p>Large applications usually have a very deep state structure when using redux - several nested levels (in the count of 100s or even 1000s). Doing a deep comparison here, perhaps several times every second, will slow down the UI. On the other hand, if we do a “shallow comparison” (where we only check if the values of the first level fields have changed), it will be much quicker, but we may miss out on updates - breaking application logic. An example of how we might miss out on updates with shallow comparison is presented below:</p>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/cbe6534caf22adf63f8afbd788e267d5/b5a09/carbon-7.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 58.22784810126582%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAYAAABiDJ37AAAACXBIWXMAAAsTAAALEwEAmpwYAAABiklEQVQoz42SaW7cMAyFfYQCY+0UtVjextM0SNH730yvsOUYKTpp+uMDadp6Ih/d/Spcy6vFt5uovZDopYJQ+owt/xpVe9liN2dCvI9VDwtsiFDGXqJ/IdW/RZVGd1OylvwdpdwrlRnKEXohDtFeto77q2P92WX1XbS7CYnII5a4IvkBhiMUMaRxkM5DWrpG7+XXFnSnMmhYEeYXuPkBmjbQ+gL/+AmaH9Ac/19w70Rpg37vwth2UAgIbRp7Tdunh59d0LE3sDFB5wnSWajQ8v4UbsgPtGchP+nQpgFu3kBpQuACDiM4THCOoTlAxwLFESaP0CHDDPMR29YbbYGNTlmCpgBtCcb5gz3XuxWOoHyAdARpdmxbknF/iBzWXCMHW3l5gLa3ykMBDxl0fwUtG3wuiMsPhLIhhQKKHrR/Oz+Q0x05jqCUYccVbn/vIjpDBjaX6sYVnCY4z1CeoeMA6yOciyBKsOSgmaFTgeEET/msM+TRYaNTxtZmsqzXGB/Mv8l3ntevn//08DesfjgMxPdf6AAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"code example\"\n        title=\"code example\"\n        src=\"/static/cbe6534caf22adf63f8afbd788e267d5/f058b/carbon-7.png\"\n        srcset=\"/static/cbe6534caf22adf63f8afbd788e267d5/c26ae/carbon-7.png 158w,\n/static/cbe6534caf22adf63f8afbd788e267d5/6bdcf/carbon-7.png 315w,\n/static/cbe6534caf22adf63f8afbd788e267d5/f058b/carbon-7.png 630w,\n/static/cbe6534caf22adf63f8afbd788e267d5/40601/carbon-7.png 945w,\n/static/cbe6534caf22adf63f8afbd788e267d5/78612/carbon-7.png 1260w,\n/static/cbe6534caf22adf63f8afbd788e267d5/b5a09/carbon-7.png 1360w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<p>In the if statement above, the UI won’t update, even though we intended to change the state. This is because the reference of <code class=\"language-text\">newState.profession</code> is equal to oldState.profession.</p>\n<p>Also notice above that when we do <code class=\"language-text\">oldState.profession !== newState.profession</code> or <code class=\"language-text\">newState !== oldState</code>, we are actually checking if their reference (and not value) is the same (they are all objects).</p>\n<h3 id=\"optimising-with-the-immutability-rule\" style=\"position:relative;\"><a href=\"#optimising-with-the-immutability-rule\" aria-label=\"optimising with the immutability rule 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>Optimising with the immutability rule</h3>\n<p>The problem of rerendering could be solved if we could somehow just do a shallow reference check, without missing out on updates. This would give us the performance we need and not break the application’s logic.</p>\n<p>Based on what we saw in the previous sections, we know that “if the reference of two variables (state variables in this case) are different, their values may or may not be the same.”. What if we change this to “if and only if the reference of two variables (state variables in this case) are different, we should assume that their values are different.”. What happens now?</p>\n<p>If the above change is enforced, then to know if a state’s value has changed, we can just do a reference check like <code class=\"language-text\">oldState === newState</code> (if this is <code class=\"language-text\">false</code>, then the reference has changed). If the reference has changed, then we can assume that the values must have changed and trigger a render. If not, then we do not rerender.</p>\n<p>To enforce this assumption, we must never directly change the fields inside <code class=\"language-text\">oldState</code>. Instead, we must always create a new copy of oldState (in <code class=\"language-text\">newState</code>), just like we showed at the start of this article, and make modifications in <code class=\"language-text\">newState</code>. Since <code class=\"language-text\">newState</code> is a new object, its reference will always be different than that of <code class=\"language-text\">oldState</code>. This is known as enforcing immutability of state - exactly what redux enforces its users to do!</p>\n<h3 id=\"conclusion\" style=\"position:relative;\"><a href=\"#conclusion\" aria-label=\"conclusion 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>Conclusion</h3>\n<p>Immutability of redux state is necessary since it allows detecting redux state changes in an efficient manner. This implies that whenever we want to modify a redux state, we must create a new copy of it and do modifications to that copy - which then becomes the new redux state.</p>","frontmatter":{"date":"November 11, 2021","title":"Why is redux state immutable?","cover":"why-is-redux-state-immutable.png","author":"Rishabh Poddar","description":"This blog covers an analysis of why redux state is immutable and how you should go about modifying state in your Redux applications"},"fields":{"slug":"/why-is-redux-state-immutable/"}},"site":{"siteMetadata":{"title":"SuperTokens Blog"}}},"pageContext":{"id":"9b8888af-f9c2-535c-9fd0-4774b03a5dac","fields__slug":"/why-is-redux-state-immutable/","__params":{"fields__slug":"why-is-redux-state-immutable"}}},
    "staticQueryHashes": []}