<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Maheedhar A</title>
    <description>The latest articles on DEV Community by Maheedhar A (@maheedhar15).</description>
    <link>https://dev.to/maheedhar15</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1033965%2Fda65c8d0-f463-440d-bf9e-d19bb9c335d3.jpg</url>
      <title>DEV Community: Maheedhar A</title>
      <link>https://dev.to/maheedhar15</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/maheedhar15"/>
    <language>en</language>
    <item>
      <title>How to force an update to Components in React</title>
      <dc:creator>Maheedhar A</dc:creator>
      <pubDate>Sun, 13 Aug 2023 02:28:30 +0000</pubDate>
      <link>https://dev.to/maheedhar15/how-to-force-an-update-to-components-in-react-1dgp</link>
      <guid>https://dev.to/maheedhar15/how-to-force-an-update-to-components-in-react-1dgp</guid>
      <description>&lt;p&gt;Have you ever come across a situation in which you submit the changes to your backend and the change is not visible in your react application? If yes, then, like me, you are using the &lt;em&gt;&lt;strong&gt;useEffect&lt;/strong&gt;&lt;/em&gt; hook to retrieve the data either from the backend/localStorage.&lt;/p&gt;

&lt;p&gt;For this exact situation, there is another hook available in react called &lt;em&gt;&lt;strong&gt;useReducer()&lt;/strong&gt;&lt;/em&gt;. If you go to the official documentation of React, the definition of the useReducer hook is given as follows:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;" &lt;strong&gt;useReducer&lt;/strong&gt; is a React Hook that lets you add a reducer to your component. "&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;With it's syntax as:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialArg, init?)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;As this definition isn't very straightforward, it is not very helpful if you are a beginner. The purpose of this article is to deconstruct this definition into simpler terms.&lt;/p&gt;

&lt;p&gt;As it is easier to understand with an example, here is a simple react code which adds some data into the localStorage everytime the button is clicked.&lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [count, setCount] = useState(0);
  const [dataValues, setdataValues] = useState('');
  const [Loaded, setLoaded] = useState(false);
  useEffect(() =&amp;gt; {
    let val;
    val = JSON.parse(localStorage.getItem('DataValues') || '[]');
    setdataValues(val);
    setLoaded(true);
  }, []);
  const handleClick = () =&amp;gt; {
    const data = { source: 'meteor' };
    dataValues.push(data);
    localStorage.setItem('DataValues', JSON.stringify(dataValues));
  };

  return (
    &amp;lt;&amp;gt;
      {Loaded ? (
          &amp;lt;h1&amp;gt;React&amp;lt;/h1&amp;gt;
          &amp;lt;div className="card"&amp;gt;
            &amp;lt;button onClick={() =&amp;gt; handleClick()}&amp;gt;Click me&amp;lt;/button&amp;gt;
          &amp;lt;/div&amp;gt;
          {dataValues.map((data, index) =&amp;gt; (
            &amp;lt;div&amp;gt;
              &amp;lt;span key={index} style={{ textAlign: 'center', color: '#fff' }}&amp;gt;
                {data.source}
              &amp;lt;/span&amp;gt;
              &amp;lt;br /&amp;gt;
            &amp;lt;/div&amp;gt;
          ))}
        &amp;lt;/div&amp;gt;
      ) : (
        ''
      )}
    &amp;lt;/&amp;gt;
  );
}

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we run the development build of this application, we can observe this:&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/BiGO2LzcO9A"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;From the above video, it can be clearly observed that the changes are made visible &lt;em&gt;&lt;strong&gt;only when the website is reloaded&lt;/strong&gt;&lt;/em&gt;. This is unacceptable for single page applications. Hence, we need to find a way to force an update to the react application once we made changes to the localStorage/backend. &lt;/p&gt;

&lt;p&gt;For this exact purpose, we use the &lt;em&gt;&lt;strong&gt;useReducer&lt;/strong&gt;&lt;/em&gt; react hook. The syntax for the useReducer hook is given below:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialArg, init?)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;reducer&lt;/strong&gt;&lt;/em&gt; =&amp;gt; a function that defines how the state is updated&lt;br&gt;
&lt;em&gt;&lt;strong&gt;initialArg&lt;/strong&gt;&lt;/em&gt; =&amp;gt; sets the initial value of the state&lt;br&gt;
&lt;em&gt;&lt;strong&gt;init?&lt;/strong&gt;&lt;/em&gt; =&amp;gt; optional argument that specifies the initializer function that should return the initial state&lt;/p&gt;

&lt;p&gt;The useReducer hook once initialized sets the value of state to init(initialArg)(if init is specified) or initialArg.&lt;/p&gt;

&lt;p&gt;The changes we should make to our code to force an update is given below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const [dataValues, setdataValues] = useState('');
  const [Loaded, setLoaded] = useState(false);

  const [ignore, forceUpdate] = useReducer((x) =&amp;gt; x + 1, 0);
  useEffect(() =&amp;gt; {
    let val;
    val = JSON.parse(localStorage.getItem('DataValues') || '[]');
    setdataValues(val);
    setLoaded(true);
  }, [ignore]);
  const handleClick = () =&amp;gt; {
    const data = { source: 'meteor' };
    dataValues.push(data);
    localStorage.setItem('DataValues', JSON.stringify(dataValues));
    forceUpdate();
  };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this does is that, whenever we call &lt;strong&gt;handleClick&lt;/strong&gt;, after performing necessary actions the &lt;strong&gt;handleClick&lt;/strong&gt; calls the &lt;strong&gt;forceUpdate&lt;/strong&gt; function. The &lt;strong&gt;forceUpdate&lt;/strong&gt; updates the value of the state from its initial state. Then, we are setting dependency of the useEffect hook to the state(ignore). Hence, whenever we click the button, &lt;strong&gt;ignore&lt;/strong&gt; gets updated and then due to that the component is refreshed and we can instantly see the changes in the react application.&lt;/p&gt;

&lt;p&gt;The output now looks like:&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/cvx8CY0bKhU"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Feel free to leave a like if this article was helpful to you.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>tutorial</category>
      <category>productivity</category>
    </item>
  </channel>
</rss>
