Rules
hooks-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, { function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
} from "react";
function function Example(): nullExample() { const [const value: string[]value, const setValue: React.Dispatch<React.SetStateAction<string[]>>setValue] = useState<string[]>(initialState: string[] | (() => string[])): [string[], React.Dispatch<React.SetStateAction<string[]>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
(function generateTodos(): string[]generateTodos());
// - Don't call a function directly inside the 'useState' call. return null; } declare function function generateTodos(): string[]generateTodos(): string[];

Passing

import React, { function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
} from "react";
function function Example(): nullExample() { const [const value: string[]value, const setValue: React.Dispatch<React.SetStateAction<string[]>>setValue] = useState<string[]>(initialState: string[] | (() => string[])): [string[], React.Dispatch<React.SetStateAction<string[]>>] (+1 overload)
Returns a stateful value, and a function to update it.
@version16.8.0@see{@link https://react.dev/reference/react/useState}
useState
(() => function generateTodos(): string[]generateTodos());
Use an initializer function to avoid recreating the initial state
return null; } declare function function generateTodos(): string[]generateTodos(): string[];

Further Reading