Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
reacthooksperformanceuseeffectdependencies

Compute derived values outside useEffect

Calculate derived conditions in the render scope and pass primitives to useEffect to prevent unnecessary re-runs.

PR: Feat/FCK-2116 - Hide transaction disclaimer on profil tab on person profile #320Created: Dec 7, 2025

Bad example

Old codetsx
1function PageTracker() {
2 const location = useLocation();
3
4 useEffect(() => {
5 // Logic inside effect; depends on entire object
6 const isProfile = location.pathname === '/profile';
7 if (isProfile) {
8 analytics.track('View Profile');
9 }
10 }, [location]); // Runs on every location object reference change
11}

Explanation (EN)

The logic is inside the effect, forcing it to depend on the entire `location` object. Since objects often change reference on every render, the effect runs more often than necessary.

Objašnjenje (HR)

Logika je unutar efekta, što ga prisiljava da ovisi o cijelom `location` objektu. Budući da objekti često mijenjaju referencu pri svakom renderiranju, efekt se pokreće češće nego što je potrebno.

Good example

New codetsx
1function PageTracker() {
2 const location = useLocation();
3
4 // Calculate derived state during render
5 const isProfile = location.pathname === '/profile';
6
7 useEffect(() => {
8 if (isProfile) {
9 analytics.track('View Profile');
10 }
11 }, [isProfile]); // Runs ONLY when the boolean actually changes
12}

Explanation (EN)

The condition is calculated synchronously in the render scope. The effect now depends on a primitive boolean value, ensuring it only re-runs when the logical outcome actually changes.

Objašnjenje (HR)

Uvjet se izračunava sinkrono tijekom renderiranja. Efekt sada ovisi o primitivnoj boolean vrijednosti, osiguravajući da se ponovno pokreće samo kada se logički ishod stvarno promijeni.