Header Ads Widget

Ticker

6/recent/ticker-posts

Why Repetitive Code is Problem in React? | Why is my React code running twice?

Why Repetitive Code is Problem in React?

React code running twice
React by dinesh

Introduction

When it comes to building React applications, developers usually encounter a lot of repetitive code because similar components are used repeatedly. The situation becomes worse when your project is not maintained well, and the possible chances of mistakes are higher. This article will discuss very simple and easy ways to stop repetitive code in React.

What is redundant code?

It means writing similar or identical codes on multiple occasions. Most likely, this happens in making UI components that are alike but differ from one another through headings, descriptions, and images alone.

Why Should You Not Repeat Code?

  • Difficult Maintenance: You have to change everything when you need to make a change in some of them.
  • Error Prone: More code means more opportunities for mistakes to be made.
  • Time-Consuming: Repeatedly typing the same things takes time.
  • Slower: More runtime inefficient code can cause a slow application.
  • Less Readable: Difficult for newcomers to understand the code base.

Example of Repetitive Code

import React from "react";
import img from "../assets/home.jpg";

function Service() {
  return (
    <div className="flex justify-evenly">
      <div className="p-7">
        <div className="flex justify-center p-5">
          <div className="w-[60px] h-[60px] bg-gray-500 rounded-full p-2">
            <img src={img} className="w-full h-full object-cover rounded-full" alt="" />
          </div>
        </div>
        <div>
          <h3 className="text-center font-bold">FREE AND FAST DELIVERY</h3>
          <p className="text-center text-[12px]">Free delivery for all orders over $140</p>
        </div>
      </div>

      <div className="p-7">
        <div className="flex justify-center p-5">
          <div className="w-[60px] h-[60px] bg-gray-500 rounded-full p-2">
            <img src={img} className="w-full h-full object-cover rounded-full" alt="" />
          </div>
        </div>
        <div>
          <h3 className="text-center font-bold">24/7 CUSTOMER SERVICE</h3>
          <p className="text-center text-[12px]">Friendly 24/7 customer support</p>
        </div>
      </div>

      <div className="p-7">
        <div className="flex justify-center p-5">
          <div className="w-[60px] h-[60px] bg-gray-500 rounded-full p-2">
            <img src={img} className="w-full h-full object-cover rounded-full" alt="" />
          </div>
        </div>
        <div>
          <h3 className="text-center font-bold">MONEY BACK GUARANTEE</h3>
          <p className="text-center text-[12px]">We return money within 30 days</p>
        </div>
      </div>
    </div>
  );
}

export default Service;

What Is Wrong with This Code?

  • Replication: The structure of each of the services is the same.
  • Hard to Update: If you want to change any design. You need to do that three times.
  • Scalability Problems: The more services, the more duplicate code.

How to Cure Repetitive Code in React

To solve this problem, we can create a reusable React component. Here's how:


Step 1: Create a Reusable Component in React

import React from "react";
import img from "../assets/home.jpg";

function Service({ heading, description }) {
  return (
    <div className="p-7">
      <div className="flex justify-center p-5">
        <div className="w-[60px] h-[60px] bg-gray-500 rounded-full p-2">
          <img src={img} className="w-full h-full object-cover rounded-full" alt="" />
        </div>
      </div>
      <div>
        <h3 className="text-center font-bold">{heading}</h3>
        <p className="text-center text-[12px]">{description}</p>
      </div>
    </div>
  );
}

export default Service;


Step 2: Create an Object to Store Data

const services = {
  "FREE AND FAST DELIVERY": "Free delivery for all orders over $140",
  "24/7 CUSTOMER SERVICE": "Friendly 24/7 customer support",
  "MONEY BACK GUARANTEE": "We return money within 30 days"
};


Step 3: Render Components Using map() in React

import React from "react";
import Service from "./Service";

function ServiceList() {
  return (
    <div className="flex justify-evenly">
      {Object.keys(services).map((key) => (
        <Service key={key} heading={key} description={services[key]} />
      ))}
    </div>
  );
}

export default ServiceList;

Advantages of approach

  • With less code, you don't need to repeat the same structure.
  • Changes the design in place.
  • Flexibility: More services can be added with no extra code.
  • It can grow: it can do large jobs easily.
  • Better Readability: Neat coding is easy to read and maintain.

Smart Strategies to Reduce Repetitive Code

  • Higher-Order Components (HOCs): Wrapping components to augment functionality.
  • Custom Hooks: For reuse of logic. 
  • Compound Components: For partial sharing of state among components. 
  • Render Props: To determine at runtime what is to be re-rendered. 
  • Context API: State to be shared globally without prop drilling. 
  • Reusable Utility Functions: For logic that is used repeatedly, outside components. 

Practical Example in React Applications 

Suppose you are building an e-commerce website using React. The chances are that you will design product cards that display the product name, price, and product image. 

Why is my React code running twice?

  • Hardcoded Data: Always data should remain out of the component structure. 
  • Ignoring Reusability: When copy-paste happens more than thrice, it's time to refactor. 
  • Overcomplicating: Components are to be kept simple and concern Papam with one task. 
  • No Keys in Lists: That might lead to problems during the rendering. 
  • Overstate: Not everything needs to go into state. 
  • Performance Optimization: With React.memo, lazy loading, and code-splitting, their use would be required.

FAQs

1. What is repetitive code in React?

Most of the time, it is the same piece of code structure that is written many times but with slight modifications like different images or text.

2. How can you eliminate redundancy in writing code in React?

Making reusable components and passing dynamic data through props is the best way to avoid repetitive and duplicate code.

3. What are props in React?

Props are the short name of properties, used for transferring one component data from another in React.

4. Why is repetitive code bad?

It is very nasty for maintenance, increases bugs, and slows down development.

5. How do I know when to make a reusable component?

When you see the same structure being somewhat different, that is a really good sign for you to create a reusable component.

6. Is everything reusable?

Oh, yes, everything can be reusable but shouldn't be. Reusable components make your code cleaner and easier to manage only when it is necessary to make them reusable.

7. Why is having reusable components an advantage?

Reusable components are an advantage because they allow saving time, preventing errors, and giving good maintainability to your code.

8. How do props help to reduce the repetition of the code?

Well, props allow us to pass dynamic data through components, thus making them flexible and reusable in different scenarios.

9. What is a key prop in React and why is it important?

Key prop uses React to know which items have changed, are added, or removed, enhancing rendering performance.

10. Can I pass functions as props?

Yes, functions can be passed as props for event handling or some specific tasks in child components.

11. How wings impact an application when a key prop is not used? 

React re-renders a component non-optimally leading to some unexpected bugs or performance degradation.

12. How do I manage complex props?

By parting into smaller names an object or array could be useful for grouping the data and additional parts of a component.

13. Is using map() the only way to render lists in React?

map() is the most popular way to do this- or you can loop the data like forEach, but this doesn't directly return that data like map() does.

14. What is component composition in React? 

Component composition is a way to compose a complex UI out of small reusable components.

15. How do reusable components improve performance? 

They help reduce the code that React needs to process, thus leading to faster rendering and easier debugging.

16. Do reusable components keep a state of their own? 

Yes, reusable components can have their state with useState or other hooks if necessary.

17. State and prop difference? 

Props send a child data from a parent, whereas state is used to keep data of a component.

18. How do I give default prop values? 

You can set values for props defined to default using defaultProps or default parameters for funtion components.

19. Can props be changed after being passed to a particular component? 

No, props are read only. Instead of working with props for changing a particular value, one has to change the same in the data of the parent component.

20. What is prop drilling and how can I avoid it? 

Prop drilling means passing props down many levels of components. That's avoidable by using something like context or state management libraries such as Redux.

Post a Comment

0 Comments