Angular OnPush Gotcha: Immutable State and Real-Time Data

𝗜 𝘀𝗽𝗲𝗻𝘁 𝟰 𝗵𝗼𝘂𝗿𝘀 𝗱𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗮 "𝗴𝗵𝗼𝘀𝘁 𝗨𝗜" — 𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 𝘁𝗵𝗮𝘁 𝗿𝗲𝗳𝘂𝘀𝗲𝗱 𝘁𝗼 𝘂𝗽𝗱𝗮𝘁𝗲 𝗼𝗻𝗹𝘆 𝘁𝗼 𝗿𝗲𝗮𝗹𝗶𝘀𝗲 𝗜 𝗰𝗮𝘂𝘀𝗲𝗱 𝗶𝘁 𝗺𝘆𝘀𝗲𝗹𝗳. 1. We had a real-time dashboard in Angular showing live sensor data. Product was happy. QA was happy. Then staging broke. 2. 𝗥𝗼𝘄𝘀 𝘄𝗲𝗿𝗲𝗻'𝘁 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿𝗶𝗻𝗴 𝗮𝗳𝘁𝗲𝗿 𝗱𝗮𝘁𝗮 𝘂𝗽𝗱𝗮𝘁𝗲𝘀. The array was clearly mutating in the console. The template just… didn't care. 3. I'd switched the component to ChangeDetectionStrategy.OnPush for "performance" — without understanding what that actually means. 𝗧𝗵𝗲 𝗺𝗶𝘀𝘁𝗮𝗸𝗲: ❌ Mutating the array directly — OnPush never sees this this.sensors.push(newSensor); this.sensors[0].value = 99; With OnPush, Angular only checks a component when its input reference changes — not when you mutate the object inside it. 𝗧𝗵𝗲 𝗳𝗶𝘅: ✅ Return a new reference — Angular picks it up instantly this.sensors = [...this.sensors, newSensor]; this.sensors = this.sensors.map((s, i) => i === 0 ? { ...s, value: 99 } : s ); Or — if you're already using signals in Angular 17+ — just use a signal() and skip this mental overhead entirely. 𝗧𝗵𝗲 𝗿𝗲𝗮𝗹 𝗹𝗲𝘀𝘀𝗼𝗻: OnPush is not a magic performance button. It's a contract you promise Angular you'll treat state as immutable. Break the contract, pay in ghost UIs. 𝗔𝗱𝗼𝗽𝘁 𝗶𝘁. 𝗟𝗼𝘃𝗲 𝗶𝘁. 𝗕𝘂𝘁 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗶𝘁 𝗳𝗶𝗿𝘀𝘁. 𝗠𝘆 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝘁𝗼 𝘆𝗼𝘂 → Have you ever turned on OnPush and immediately broken something? What was your "wait, THAT was the issue?" moment? Drop it below. 👇 #Angular #TypeScript #WebDevelopment #FrontendDevelopment #SoftwareEngineering #LearnInPublic #CodingMistakes

Aashish Bhagwat is a Senior Software Engineer and Certified Angular Developer, specializing in building AI-powered web applications for startups. With a strong command of technologies including Node.js, React.js, and Laravel, Aashish delivers robust and innovative solutions. As an N8N expert, Aashish also streamlines automation workflows, enhancing operational efficiency and driving growth for emerging ventures.

Like
Reply

To view or add a comment, sign in

Explore content categories