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 (
// …
);


This content originally appeared on DEV Community and was authored by Omer Davidson

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 (
      // ...
    );
  }

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 (
      // ...
    );
  }


This content originally appeared on DEV Community and was authored by Omer Davidson


Print Share Comment Cite Upload Translate Updates
APA

Omer Davidson | Sciencx (2024-10-29T18:11:30+00:00) A useState performance tip you may not have known. Retrieved from https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/

MLA
" » A useState performance tip you may not have known." Omer Davidson | Sciencx - Tuesday October 29, 2024, https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/
HARVARD
Omer Davidson | Sciencx Tuesday October 29, 2024 » A useState performance tip you may not have known., viewed ,<https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/>
VANCOUVER
Omer Davidson | Sciencx - » A useState performance tip you may not have known. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/
CHICAGO
" » A useState performance tip you may not have known." Omer Davidson | Sciencx - Accessed . https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/
IEEE
" » A useState performance tip you may not have known." Omer Davidson | Sciencx [Online]. Available: https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/. [Accessed: ]
rf:citation
» A useState performance tip you may not have known | Omer Davidson | Sciencx | https://www.scien.cx/2024/10/29/a-usestate-performance-tip-you-may-not-have-known/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.