<?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: Harsh</title>
    <description>The latest articles on DEV Community by Harsh (@harshsolanki05).</description>
    <link>https://dev.to/harshsolanki05</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%2F1763659%2F0a257968-1c87-4102-b28a-512c4090f231.jpg</url>
      <title>DEV Community: Harsh</title>
      <link>https://dev.to/harshsolanki05</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/harshsolanki05"/>
    <language>en</language>
    <item>
      <title>How to Prevent Unnecessary React Component Re-Rendering</title>
      <dc:creator>Harsh</dc:creator>
      <pubDate>Mon, 09 Sep 2024 07:38:15 +0000</pubDate>
      <link>https://dev.to/harshsolanki05/how-to-prevent-unnecessary-react-component-re-rendering-3jg6</link>
      <guid>https://dev.to/harshsolanki05/how-to-prevent-unnecessary-react-component-re-rendering-3jg6</guid>
      <description>&lt;p&gt;Understanding how &lt;a href="https://reactnative.dev/" rel="noopener noreferrer"&gt;React Native &lt;/a&gt;renders components is essential for building efficient and performant applications. When a component’s state or props change, React automatically updates the User Interface(UI) to reflect those changes. As a result, React calls the component's render method again to generate the updated UI representation.&lt;/p&gt;

&lt;p&gt;In this article, we will explore three React Hooks and how they prevent unnecessary renderings in React&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;useMemo&lt;/li&gt;
&lt;li&gt;useCallback&lt;/li&gt;
&lt;li&gt;useRef&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These tools allow us to optimize our code by avoiding unnecessary re-renders, improving performance, and storing values efficiently.&lt;/p&gt;

&lt;p&gt;By the end of this article, we'll better understand how to make our React applications faster and more responsive using these handy React hooks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using React's useMemo
&lt;/h2&gt;

&lt;p&gt;In React, &lt;code&gt;useMemo&lt;/code&gt; can prevent unnecessary re-renderings and optimize performance.&lt;/p&gt;

&lt;p&gt;Let's explore how the &lt;code&gt;useMemo&lt;/code&gt; hook can prevent unnecessary re-renders in our React components.&lt;/p&gt;

&lt;p&gt;By memorizing the result of a function and tracking its dependencies, useMemo ensures that the process is recomputed only when necessary.&lt;/p&gt;

&lt;p&gt;Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useMemo, useState } from 'react';

    function Page() {
      const [count, setCount] = useState(0);
      const [items] = useState(generateItems(300));

      const selectedItem = useMemo(() =&amp;gt; items.find((item) =&amp;gt; item.id === count), [
        count,
        items,
      ]);

      function generateItems(count) {
        const items = [];
        for (let i = 0; i &amp;lt; count; i++) {
          items.push({
            id: i,
            isSelected: i === count - 1,
          });
        }
        return items;
      }

      return (
        &amp;lt;div className="tutorial"&amp;gt;
          &amp;lt;h1&amp;gt;Count: {count}&amp;lt;/h1&amp;gt;
          &amp;lt;h1&amp;gt;Selected Item: {selectedItem?.id}&amp;lt;/h1&amp;gt;
          &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      );
    }

    export default Page;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above is a React component called Page that uses useMemo to optimize the selectedItem calculation.&lt;/p&gt;

&lt;p&gt;Here's the explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The component maintains a state variable &lt;code&gt;count&lt;/code&gt; using the useState hook.&lt;/li&gt;
&lt;li&gt;The items state is initialized using the useState hook with the result of the generateItemsfunction.&lt;/li&gt;
&lt;li&gt;The selectedItem is calculated using useMemo, which memorizes the result of the items.find operation. It only re-calculates when either count or items change.&lt;/li&gt;
&lt;li&gt;The generateItems function generates an array of items based on the given count.&lt;/li&gt;
&lt;li&gt;The component renders the current &lt;strong&gt;count&lt;/strong&gt; value, the selectedItem id, and a button to increment the count.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using useMemo optimizes performance by memoizing the result of the items.find operation. It ensures that the calculation of selectedItem is only performed when the dependencies (count or items) change, preventing unnecessary re-calculations on subsequent renders.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Memoization should be employed selectively for computationally intensive operations, as it introduces additional overhead to the rendering process.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Using React's useCallback
&lt;/h2&gt;

&lt;p&gt;The useCallback hook in React allows for the memoization of functions, preventing them from being recreated during each component render. By utilizing useCallback. a part is created only once and reused in subsequent renders as long as its dependencies remain unchanged.&lt;/p&gt;

&lt;p&gt;Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useCallback, memo } from 'react';

    const allColors = ['red', 'green', 'blue', 'yellow', 'orange'];

    const shuffle = (array) =&amp;gt; {
      const shuffledArray = [...array];
      for (let i = shuffledArray.length - 1; i &amp;gt; 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
      }
      return shuffledArray;
    };

    const Filter = memo(({ onChange }) =&amp;gt; {
      console.log('Filter rendered!');

      return (
        &amp;lt;input
          type='text'
          placeholder='Filter colors...'
          onChange={(e) =&amp;gt; onChange(e.target.value)}
        /&amp;gt;
      );
    });

    function Page() {
      const [colors, setColors] = useState(allColors);
      console.log(colors[0])

      const handleFilter = useCallback((text) =&amp;gt; {
        const filteredColors = allColors.filter((color) =&amp;gt;
          color.includes(text.toLowerCase())
        );
        setColors(filteredColors);
      }, [colors]);


      return (
        &amp;lt;div className='tutorial'&amp;gt;
        &amp;lt;div className='align-center mb-2 flex'&amp;gt;
          &amp;lt;button onClick={() =&amp;gt; setColors(shuffle(allColors))}&amp;gt;
            Shuffle
          &amp;lt;/button&amp;gt;
          &amp;lt;Filter onChange={handleFilter} /&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;ul&amp;gt;
          {colors.map((color) =&amp;gt; (
            &amp;lt;li key={color}&amp;gt;{color}&amp;lt;/li&amp;gt;
          ))}
        &amp;lt;/ul&amp;gt;
      &amp;lt;/div&amp;gt;
      );
    }

    export default Page;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above demonstrates a simple color filtering and shuffling functionality in a React component. Let's go through it step by step:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The initial array of colors is defined as allColors.&lt;/li&gt;
&lt;li&gt;The shuffle function takes an array and shuffles its elements randomly. It uses the Fisher-Yates algorithm to achieve shuffling.&lt;/li&gt;
&lt;li&gt;The Filter component is a memoized functional component that renders an input element. It receives an onChange prop and triggers the callback function when the input value changes.&lt;/li&gt;
&lt;li&gt;The Page component is the main component that renders the color filtering and shuffling functionality.&lt;/li&gt;
&lt;li&gt;The state variable colors are initialized using the useState hook, with the initial value set to allColors. It represents the filtered list of colors.&lt;/li&gt;
&lt;li&gt;The handleFilter function is created using the useCallback hook. It takes a text parameter and filters the allColors array based on the provided text. The filtered colors are then set using the setColors function from the useState hook. The dependency array [colors] ensures that the handleFilter function is only recreated if the colors state changes, optimizing performance by preventing unnecessary re-renders.&lt;/li&gt;
&lt;li&gt;Inside the Page component is a button for shuffling the colors. When the button clicks, it calls the setColors function with the shuffled array of allColors.&lt;/li&gt;
&lt;li&gt;The Filter component is rendered with the onChange prop set to the handleFilter function.&lt;/li&gt;
&lt;li&gt;Finally, the colors array is mapped to render the list of color items as &lt;/li&gt;
&lt;li&gt; elements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The useCallback hook is used to memoize the handleFilter function, which means the function is only created once and reused on subsequent renders if the dependencies (in this case, the colors state) remain the same.&lt;/p&gt;

&lt;p&gt;This optimization prevents unnecessary re-renders of child components that receive the handleFilter function as a prop, such as the Filter component.&lt;br&gt;
It ensures that the Filter component is not re-rendered if the colors state hasn't changed, improving performance.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using React's useRef
&lt;/h2&gt;

&lt;p&gt;Another approach to enhance performance in React applications and avoid unnecessary re-renders is using the useRef hook. Using useRef, we can store a mutable value that persists across renders, effectively preventing unnecessary re-renders.&lt;/p&gt;

&lt;p&gt;This technique allows us to maintain a reference to a value without triggering component updates when that value changes. By leveraging the mutability of the reference, we can optimize performance in specific scenarios.&lt;/p&gt;

&lt;p&gt;Consider the following example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useState } from 'react';

function App() {
  const [name, setName] = useState('');
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input
        type="text"
        value={name}
        onChange={(e) =&amp;gt; setName(e.target.value)}
        ref={inputRef}
      /&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Focus&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The example above has a simple input field and a button. The useRef hook creates a ref called inputRef. As soon as the button is clicked, the handleClick function is called, which focuses on the input element by accessing the current property of the inputRef ref object. As such, it prevents unnecessary rerendering of the component when the input value changes.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To ensure optimal use of &lt;code&gt;useRef,&lt;/code&gt; reserve it solely for mutable values that do not impact the component's rendering. If a mutable value influences the component's rendering, it should be stored within its state instead.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Throughout this tutorial, we explored the concept of React re-rendering and its potential impact on the performance of our applications. We delved into the optimization techniques that can help mitigate unnecessary re-renders. React offers a variety of hooks that enable us to enhance the performance of our applications. We can effectively store values and functions between renders by leveraging these hooks, significantly boosting React application performance.&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>javascript</category>
      <category>frontend</category>
      <category>performance</category>
    </item>
    <item>
      <title>Getting Started with React Native: Building Your First App</title>
      <dc:creator>Harsh</dc:creator>
      <pubDate>Thu, 11 Jul 2024 05:58:45 +0000</pubDate>
      <link>https://dev.to/harshsolanki05/getting-started-with-react-native-building-your-first-app-4bkj</link>
      <guid>https://dev.to/harshsolanki05/getting-started-with-react-native-building-your-first-app-4bkj</guid>
      <description>&lt;p&gt;React Native is a powerful framework that allows you to build mobile applications using JavaScript and React. In this blog post, we'll walk through the steps to create a simple React Native app from scratch. Whether you're a seasoned React developer or just getting started, this guide will help you get up and running with React Native.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Prerequisites&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Before we dive into the code, make sure you have the following installed on your system:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Node.js: Download and install from nodejs.org.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;2.Watchman: A file-watching service. Install using Homebrew on macOS: brew install watchman.&lt;/p&gt;

&lt;p&gt;3.React Native CLI: Install globally using npm: npm install -g react-native-cli.&lt;/p&gt;

&lt;p&gt;4.Xcode: Required for iOS development. Install from the Mac App Store.&lt;/p&gt;

&lt;p&gt;5.Android Studio: Required for Android development. Download and install from developer.android.com.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Setting Up Your First React Native Project&lt;/strong&gt;
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Initialize a New Project: Open your terminal and run the following command to create a new React Native project:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx react-native init MyFirstApp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace MyFirstApp with your desired project name.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Navigate to the Project Directory:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd MyFirstApp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Running the App:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;For iOS: Make sure you have Xcode installed. Then, run:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx react-native run-ios
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;For Android: Make sure you have an Android emulator running or a physical device connected. Then, run:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx react-native run-android
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;## Building a Simple Counter App&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's create a simple counter app to get a feel for how React Native works. We'll use React hooks to manage the state of our counter.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open the App.js/App.tsx File: This file is the entry point of your React Native application. Replace its contents with the following code:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  const [count, setCount] = useState(0);

  return (
    &amp;lt;View style={styles.container}&amp;gt;
      &amp;lt;Text style={styles.counterText}&amp;gt;Count: {count}&amp;lt;/Text&amp;gt;
      &amp;lt;Button title="Increase" onPress={() =&amp;gt; setCount(count + 1)} /&amp;gt;
      &amp;lt;Button title="Decrease" onPress={() =&amp;gt; setCount(count - 1)} /&amp;gt;
    &amp;lt;/View&amp;gt;
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  counterText: {
    fontSize: 32,
    marginBottom: 16,
  },
});

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

&lt;/div&gt;



&lt;p&gt;Save and Run the App: Save the changes and run your app again using the commands mentioned earlier (&lt;code&gt;npx react-native run-ios&lt;/code&gt; or &lt;code&gt;npx react-native run-android&lt;/code&gt;). You should see a simple app with a counter and buttons to increase and decrease the count.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;&lt;em&gt;Conclusion&lt;/em&gt;&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Congratulations! You've successfully created your first React Native app. From here, you can start exploring more advanced features and libraries to build more complex applications. React Native has a vibrant community and a rich ecosystem of libraries and tools that can help you along the way.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you have any questions or run into issues, feel free to leave a comment below or reach out to the React Native community. Happy coding!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>beginners</category>
      <category>react</category>
      <category>typescript</category>
      <category>reactnative</category>
    </item>
  </channel>
</rss>
