React
react/no-derived-state-effect
Values computed from props or state are calculated during render, not copied into state by an effect.
umiarkowanaręcznefe-react
Dlaczego
useEffect(() => setFullName(first + ' ' + last), [first, last]) renders once with a stale value, then again with the right one: an extra render, a flash of wrong content and a second source of truth that drifts.
Poprawka
Compute it in the component body: const fullName = first + ' ' + last. If the computation is expensive, wrap it in useMemo (or let React Compiler memoize it). Reset state on a prop change with a key, and handle user events in the event handler, not in an effect.
Przykłady
// bad
const [visible, setVisible] = useState([])
useEffect(() => setVisible(todos.filter((t) => !t.done)), [todos])
// good
const visible = todos.filter((t) => !t.done)Źródła
Fakty
- Identyfikator
react/no-derived-state-effect- Waga
- umiarkowana
- Sprawdzanie
- ręczne ocenia człowiek; raport podaje to jako listę kontrolną
- Dotyczy plików
jsx- Tylko w projektach z
reactnext- Uczy jej skill
fe-reactReact components- Od wersji
- 0.1.0
Przeczytaj w terminalu
npx github:dawidolko/frontend-skills explain react/no-derived-state-effect