no-set-state-in-use-effect
Rule category
Correctness.
What it does
Disallow direct calls to the set function of useState in useEffect.
Why is this bad?
Calling setState directly in useEffect is a common bad practice. It can lead to infinite update loops and other side effects.
Examples
Failing
import React, { function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): voidAccepts a function that contains imperative, possibly effectful code.useEffect, function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)Returns a stateful value, and a function to update it.useState } from "react";
function function Example(): nullExample() {
const [const value: numbervalue, const setValue: React.Dispatch<React.SetStateAction<number>>setValue] = useState<number>(initialState: number | (() => number)): [number, React.Dispatch<React.SetStateAction<number>>] (+1 overload)Returns a stateful value, and a function to update it.useState(0);
function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): voidAccepts a function that contains imperative, possibly effectful code.useEffect(() => {
const setValue: (value: React.SetStateAction<number>) => voidsetconst setValue: (value: React.SetStateAction<number>) => voidValue(const value: numbervalue + 1);
// - Do not call the 'set' function of 'useState' directly in 'useEffect'.
}, []);
return null;
}Passing
import React, { function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): voidAccepts a function that contains imperative, possibly effectful code.useEffect, function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)Returns a stateful value, and a function to update it.useState } from "react";
function function Example(): nullExample() {
const [const value: numbervalue, const setValue: React.Dispatch<React.SetStateAction<number>>setValue] = useState<number>(initialState: number | (() => number)): [number, React.Dispatch<React.SetStateAction<number>>] (+1 overload)Returns a stateful value, and a function to update it.useState(0);
function useEffect(effect: React.EffectCallback, deps?: React.DependencyList): voidAccepts a function that contains imperative, possibly effectful code.useEffect(() => {
const const onLoad: () => voidonLoad = () => {
const setValue: (value: React.SetStateAction<number>) => voidsetValue(const value: numbervalue + 1);
};
// ...
}, []);
return null;
}