Home Web Front-end JS Tutorial eact Tricks to Improve Code Quality and Performance

eact Tricks to Improve Code Quality and Performance

Jan 03, 2025 am 01:38 AM

eact Tricks to Improve Code Quality and Performance

React is a powerful JavaScript library for building user interfaces, and with just a few tricks, you can write cleaner, more efficient, and maintainable code. In this article, we'll explore five essential React tricks that will help you write more performant and readable code.


1. Use Ternary Operators Instead of AND (&&) Operators to Render Elements

In React, it’s common to conditionally render components or elements based on certain conditions. However, using the && operator for conditional rendering can be tricky when the evaluated expression results in a falsy value (e.g., false, null, undefined, 0, or ''). To avoid unintended rendering behavior, prefer using a ternary operator.

Example of && Behavior:

Using && in conditional rendering:

{0 && <h1>Hello world 5</h1>}
{0 ? <h1>Hello world 6</h1> : null}
Copy after login
Copy after login
Copy after login
  • The first example ({0 &&

    Hello world 5

    }) will render 0 in the UI because 0 is a falsy value in JavaScript, and React will interpret this as false. However, instead of rendering nothing, React will render the falsy value (0) itself.

  • The second example ({0 ?

    Hello world 6

    : null}) will render nothing. Since the condition is 0 (which is falsy), the ternary operator will evaluate to null, and React will not render anything.

Better Approach with Ternary Operator:

Instead of relying on the && operator, you can use a ternary operator to ensure you render the correct fallback content, especially when the condition is falsy.

{0 ? <h1>Hello world 5</h1> : null}
Copy after login
Copy after login

In this case, if the condition is falsy (0), React will render null, which results in nothing being rendered, providing more predictable and intended behavior.


2. Lazy Initializer with useState

React’s useState hook can take a function as its initial value, allowing you to lazily initialize the state. This is particularly useful when the initial state is expensive to compute or when it depends on some computation that should only run once.

Why Use Lazy Initialization?

  • Performance Improvement: If the initial state involves expensive computations or data fetching, lazy initialization helps to defer that cost until it is actually needed.
  • Avoid Unnecessary Computations: The function you pass to useState as the initial value will only be executed once during the component mount, and it won’t be recomputed during subsequent renders.

Example:

{0 && <h1>Hello world 5</h1>}
{0 ? <h1>Hello world 6</h1> : null}
Copy after login
Copy after login
Copy after login

In this example:

  • useState(() => Math.random()) will call the function only once, on the initial render.
  • This ensures that the random number generation only occurs once, improving performance if the computation was expensive.

3. Use Lazy Load Components to Improve Performance

React's React.lazy() and Suspense are great tools for lazy loading components, which helps split your JavaScript into smaller bundles and loads them only when needed. This significantly reduces the initial load time and improves the performance of your app.

Example:

{0 ? <h1>Hello world 5</h1> : null}
Copy after login
Copy after login

In this example:

  • React.lazy() allows you to dynamically import LazyComponent.
  • The Suspense component is used to display a loading state until the lazy-loaded component is fully rendered.

By using lazy loading, your app will only load the components necessary for the initial render and fetch others on-demand, enhancing performance, especially in large applications.


4. Using Optional Chaining in JavaScript

If you're working with JavaScript, optional chaining (?.) is a lifesaver when accessing deeply nested properties on objects. It prevents errors that occur when trying to access properties of undefined or null. Optional chaining is available in modern JavaScript and allows you to safely access properties without having to manually check for null or undefined.

Example:

import React, { useState } from 'react';

const ExpensiveComponent: React.FC = () => {
  const [count, setCount] = useState(() => {
    // Expensive computation
    console.log('Computing initial state');
    return Math.random(); // For example, generate a random number
  });

  return <div>Initial Random Value: {count}</div>;
};

export default ExpensiveComponent;
Copy after login

In this example:

  • data?.info?.address safely accesses the address property without throwing an error if data or info is undefined or null.
  • The ?? operator provides a default value if address is undefined.

Without optional chaining, you’d need to manually check each level, which can quickly lead to cluttered and harder-to-read code. Optional chaining keeps it clean and error-free.


5. Use useRef for Forms to Avoid Re-renders

In React, when working with forms and you don’t need the component to re-render on each input change, it's better to use useRef instead of useState. useRef stores the value of the input field directly and does not trigger a re-render when the value changes, making it more performant for large forms.

Example:

{0 && <h1>Hello world 5</h1>}
{0 ? <h1>Hello world 6</h1> : null}
Copy after login
Copy after login
Copy after login

In this TypeScript example:

  • useRef is used to keep track of the input value without causing the component to re-render on every input change.
  • nameRef.current is used to directly access the input’s value when the form is submitted.

Using useRef is particularly useful when the form value does not need to trigger re-renders for validation or dynamic updates, making it an excellent choice for performance-sensitive forms.


Conclusion

By applying these five React tricks in your code, you can significantly improve performance, readability, and maintainability. Here’s a quick recap:

  1. Use ternary operators for conditional rendering instead of &&.
  2. Take advantage of lazy initialization in useState.
  3. Implement lazy loading for components to improve initial load times.
  4. Use optional chaining for safer property access in JavaScript.
  5. Use useRef in forms to avoid unnecessary re-renders.

With these techniques, your React applications will be more efficient and easier to maintain, leading to better user experiences and smoother development. Happy coding!

The above is the detailed content of eact Tricks to Improve Code Quality and Performance. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles