Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
reacthooksuseeffectperformancestate-management

Trigger side effects in event handlers, not useEffect

Place logic triggered by user interactions directly in event handlers instead of watching state with useEffect.

PR: Feat/FCK-1941 - Add Phone App modal after Enter Code form #667Created: Dec 7, 2025

Bad example

Old codetsx
1const [step, setStep] = useState(0);
2
3// BAD: The effect runs after every render where 'step' changes.
4// This obscures the data flow and causes unnecessary cycles.
5useEffect(() => {
6 onStepChange(step);
7 analytics.track('step_view', { step });
8}, [step, onStepChange]);
9
10const handleNext = () => {
11 setStep((prev) => prev + 1);
12};

Explanation (EN)

Using useEffect to sync state with callbacks creates a 'waterfall' of updates. The state changes, React renders, then the effect runs. This makes code harder to follow and can trigger redundant renders or behaviors.

Objašnjenje (HR)

Korištenje useEffect-a za sinkronizaciju stanja s callbackovima stvara 'vodopad' ažuriranja. Stanje se mijenja, React renderira, a tek onda se izvršava efekt. To otežava praćenje koda i može uzrokovati suvišna renderiranja.

Good example

New codetsx
1const [step, setStep] = useState(0);
2
3// GOOD: The side effect is triggered directly by the user action.
4// The cause (click) and effect (callback/analytics) are colocated.
5const handleNext = () => {
6 const nextStep = step + 1;
7 setStep(nextStep);
8 onStepChange(nextStep);
9 analytics.track('step_view', { step: nextStep });
10};

Explanation (EN)

By triggering the side effect in the event handler, you avoid the useEffect lifecycle entirely. The logic executes immediately when the user interacts, making the data flow explicit and predictable.

Objašnjenje (HR)

Pokretanjem nuspojave u event handleru izbjegavate useEffect životni ciklus. Logika se izvršava odmah pri interakciji korisnika, čineći tijek podataka jasnim i predvidljivim.

Notes (EN)

See React docs: 'You Might Not Need an Effect'. If you need to handle the initial state (on mount), separate that logic or use a specific initialization effect, but keep user-triggered updates in handlers.

Bilješke (HR)

Pogledaj React dokumentaciju: 'You Might Not Need an Effect'. Ako trebaš obraditi početno stanje (pri mountanju), odvoji tu logiku ili koristi specifičan efekt za inicijalizaciju, ali ažuriranja potaknuta od strane korisnika zadrži u handlerima.