Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Don't guard setState against setting the same value
Skip if (x !== next) setX(next) guards; React bails out on identical values, and reading x in an empty-deps callback risks a stale closure.
Bad example
| 1 | const connect = useCallback(() => { |
| 2 | es.onopen = () => { |
| 3 | if (failed) setFailed(false); // `failed` is stale (empty deps); guard is pointless |
| 4 | }; |
| 5 | }, []); |
Explanation (EN)
The guard adds no benefit (React skips re-render when the value is unchanged) and reading `failed` from a callback with empty deps captures a stale initial value.
Objašnjenje (HR)
Guard ne donosi korist (React preskace re-render kad je vrijednost ista), a citanje `failed` iz callbacka s praznim deps hvata zastarjelu pocetnu vrijednost.
Good example
| 1 | const connect = useCallback(() => { |
| 2 | es.onopen = () => { |
| 3 | setFailed(false); // safe: React bails out if already false |
| 4 | }; |
| 5 | }, []); |
Explanation (EN)
Setting the value directly is correct and simpler; if it's already false React does nothing.
Objašnjenje (HR)
Izravno postavljanje vrijednosti je ispravno i jednostavnije; ako je vec false, React ne radi nista.
Exceptions / Tradeoffs (EN)
A guard is justified when the setter call itself is expensive to reach (e.g. avoids running other side effects), not merely to avoid a same-value render.
Iznimke / Tradeoffi (HR)
Guard je opravdan kad je sam poziv settera skup za dosegnuti (npr. izbjegava pokretanje drugih nuspojava), a ne samo da izbjegne render s istom vrijednoscu.