Home > Web Front-end > JS Tutorial > body text

A useState performance tip you may not have known

Patricia Arquette
Release: 2024-10-30 23:50:29
Original
256 people have browsed it

A useState performance tip you may not have known

Let's say we have a react component with a useState inside it.

const expensiveCalculation = () => {
  // ...
}

export default function AboutPage() {
  const [state, setState] = useState(expensiveCalculation())

    return (
      // ...
    );
  }
Copy after login

We initiate the state with the result of the expensiveCalculation function.
Every time the component re-renders, the function expensiveCalculation will run even though we only need it's result as the initial value of useState. The function's result will not be used.

To avoid the expensive calculation during re-renders, pass the function itself without calling it. react is smart enough to invoke the function itself on mount and not every render.

const expensiveCalculation = () => {
  // ...
}

export default function AboutPage() {
  const [state, setState] = useState(expensiveCalculation)

    return (
      // ...
    );
  }
Copy after login

The above is the detailed content of A useState performance tip you may not have known. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!