DocumentationRuleshooks-extra/prefer-use-state-lazy-initialization

prefer-use-state-lazy-initialization

Rule category

Perf.

What it does

Warns function calls made inside useState calls.

Why is this bad?

A function can be invoked inside a useState call to help create its initial state. However, subsequent renders will still invoke the function while discarding its return value. This is wasteful and can cause performance issues if the function call is expensive.

To combat this issue React allows useState calls to use an initializer function which will only be called on the first render.

Examples

Failing

import React, { useState } from "react";
 
function Example() {
  const [value, setValue] = useState(generateTodos());
  //                                 ^^^^^^^^^^^^^^^
  //                                 - Don't call a function directly inside the 'useState' call.
 
  return null;
}
 
declare function generateTodos(): string[];

Passing

import React, { useState } from "react";
 
function Example() {
// @annotate: Use an initializer function to avoid recreating the initial state
  const [value, setValue] = useState(() => generateTodos());
 
  return null;
}
 
declare function generateTodos(): string[];

Further reading