Home > Web Front-end > JS Tutorial > How to use the useTransition hook the improve performance in React

How to use the useTransition hook the improve performance in React

WBOY
Release: 2024-08-22 18:40:05
Original
931 people have browsed it

How to use the useTransition hook the improve performance in React

React is a popular JavaScript library for building user interfaces. It’s known for efficiency and focus on creating reusable UI components. one of key features in React is the introduction of hooks which are function that hooks into React state. on of those hooks is the useTransition hook. This hook allows the state change to happen without blocking the interface which result in smooth experience.

Understanding useTransition hook

To understand the useTransition hook better we will look into the following example.

import {useState} from "react"

const App = () => {
  const [post, setPost] = useState(undefined)

  const fetchData = async () => {
    await fetch("https://jsonplaceholder.org/posts/1")
      .then((result) => result.json())
      .then((result) => setPost(result))
  }

  return(
    <div>
      {post !== undefined && (
      <div className="post-card">
        <h2>{post?.title}</h2>
        <image src={post?.image} />
        <p>{post?.content}</p>
      </div>
      )}
      <button onClick={fetchData}>
        Get post
      </button>
    </div>
  )
}

export default App; 
Copy after login

when the use click the button depending on how slow the internet is or how heavy the task executed inside the fetchData function, The UI may freeze durring the fetch task which will result in poor user experience. also there is the possibility of user spamming the button in case if you don’t want the user abuse your application. Also the application don’t show the user any indication that their is an operation in process.

Those issues can easily be fixed using the useTransition hook we can update the previous code into something like this.

import {useState, useTransition} from "react"
import {ImSpinner2} from "react-icons/im"

const App = () => {
  const [pending, startTransition] = useTransition()
  const [post, setPost] = useState({})

  const fetchData = () => {
    startTransition( async () => {
      await fetch("https://jsonplaceholder.org/posts/1")
        .then((result) => result.json())
        .then((result) => setPost(result))
    })
  }

  return(
    <div>
      {post !== undefined && (
      <div className="post-card">
        <h2>{post.title}</h2>
        <image src={post.image} />
        <p>{post.content}</p>
      </div>
      )}
      <button
        disabled={pending} 
        onClick={fetchData}>
        {pending ? <ImSpinner2 className="animate-spin" /> : "Get post" }
      </button>
    </div>
  )
}

export default App; 
Copy after login

The invoked useTransition hook return two values: pending which value will be true if the task is been executed and startTransition function contains the task that my be interrupted by more urgent tasks.

In the example above we wrapped the fetch request in side an asynchronous arrow function that is inside the startTransition function.

and in the button we modify it in such way that includes a disabled attributes that is linked to pending and we changed the label of the button to show a spinner when the task is pending and show the label “Get post” when the task is not pending.

This result in smooth user experience and provide a better performance and secure your application from user misbehavior.

Conclusion

The useTransition hook is a game-changer for building performant React application with smooth user experience. It ensures that the UI remain responsive during potentially slow operations and preventing UI freeze which enhances the overall user experience.

The above is the detailed content of How to use the useTransition hook the improve performance in React. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template