Component Purity

Back

Loading concept...

🍳 Component Purity: The Kitchen That Never Gets Messy

The Magic Recipe Machine

Imagine you have a magical recipe machine in your kitchen. You put in flour, eggs, and sugar β€” and it ALWAYS gives you the same delicious cake. No surprises. No explosions. No mess on the walls.

That’s what a pure component is in React!


🎯 What is a Pure Component?

A pure component is like a perfect robot chef:

  1. Same ingredients = Same dish (always!)
  2. Never sneaks into the fridge while cooking
  3. Doesn’t change anything in the kitchen
// 🟒 PURE: Same input = Same output
function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

// Give it "Emma" β†’ Always shows "Hello, Emma!"
// Give it "Liam" β†’ Always shows "Hello, Liam!"

The Golden Rule

A pure function does ONE thing: takes input, returns output. Nothing else!

graph TD A["Props Input"] --> B["Pure Component"] B --> C["Same JSX Output"] A2["Same Props"] --> B B --> C2["Identical Result!"]

⚠️ Side Effects: The Kitchen Saboteurs

What’s a Side Effect?

A side effect is when your robot chef does sneaky things while cooking:

  • πŸ“± Makes a phone call
  • πŸšͺ Opens the refrigerator
  • πŸ“ Writes on the shopping list
  • ⏰ Checks what time it is

These aren’t bad things! But they shouldn’t happen while cooking (rendering).

πŸ”΄ Bad: Side Effects INSIDE Render

// ❌ IMPURE: Doing sneaky things while rendering!
function BadCounter({ count }) {
  // Side effect: Changing something outside!
  document.title = `Count: ${count}`;

  // Side effect: Making network request!
  fetch('/api/log', { method: 'POST' });

  return <p>Count is {count}</p>;
}

Why is this bad?

  • React might render your component many times
  • Each render triggers those side effects again and again
  • Your title changes unexpectedly
  • You send 10 network requests instead of 1!

🟒 Good: Side Effects in useEffect

// βœ… PURE: Render just returns JSX
function GoodCounter({ count }) {
  // Side effects go in useEffect (after render)
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return <p>Count is {count}</p>;
}

🧹 Keeping Components Pure

The Three Promises of Purity

Promise Meaning Example
🎯 Predictable Same props = Same result Greeting({name: "Jo"}) always shows β€œHello, Jo!”
🚫 No Mutations Never change props or outside variables Don’t modify arrays or objects passed in
πŸ”‡ No Side Effects Don’t talk to the outside world during render No fetch, no localStorage, no DOM changes

Common Purity Mistakes

❌ Mutating Props

// BAD: Changing the prop directly!
function BadList({ items }) {
  items.push("sneaky item"); // NO!
  return <ul>{items.map(i => <li>{i}</li>)}</ul>;
}

βœ… Create New Data Instead

// GOOD: Make a new array
function GoodList({ items }) {
  const allItems = [...items, "new item"];
  return <ul>{allItems.map(i => <li>{i}</li>)}</ul>;
}

❌ Reading Changing Values

// BAD: Reading random/time during render
function BadClock() {
  const now = new Date(); // Different every time!
  return <p>{now.toLocaleTimeString()}</p>;
}

βœ… Pass Values as Props

// GOOD: Time comes from outside
function GoodClock({ time }) {
  return <p>{time.toLocaleTimeString()}</p>;
}

πŸ† PureComponent Class

The Automatic Optimizer

Before React hooks, we had class components. PureComponent was like giving your robot chef a memory:

β€œHey, I already made this exact cake 5 minutes ago. Same ingredients. I’ll just serve the one I made before!”

import { PureComponent } from 'react';

class OptimizedGreeting extends PureComponent {
  render() {
    console.log('Rendering...');
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

How It Works

graph TD A["New Props Arrive"] --> B{Same as before?} B -->|Yes| C["Skip Render! πŸš€"] B -->|No| D["Render Component"] D --> E["Show Updated UI"]

PureComponent Does Shallow Comparison

What it compares How
Strings, Numbers "hello" === "hello" βœ…
Objects Same reference? obj1 === obj2
Arrays Same reference? arr1 === arr2

⚠️ Important! Shallow means it only checks the β€œaddress” of objects, not their contents.

// These look the same but are DIFFERENT to PureComponent
const user1 = { name: "Jo" };
const user2 = { name: "Jo" };

user1 === user2  // false! Different objects

Modern Equivalent: React.memo

Today, we use React.memo for function components:

import { memo } from 'react';

// Same optimization, modern style!
const OptimizedGreeting = memo(function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
});

🎬 Quick Story Recap

Concept Kitchen Analogy
Pure Component Robot chef that always makes the same dish from the same ingredients
Side Effect Sneaky actions (phone calls, checking fridge) during cooking
Side Effects in Render Making phone calls while whisking eggs β€” chaos!
useEffect β€œAfter you finish cooking, THEN make the phone call”
PureComponent Chef with memory: β€œI made this before, here’s your cake!”
React.memo Modern version of the memory chef

πŸ’‘ Remember This!

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  PURE COMPONENT = PREDICTABLE       β”‚
β”‚  ─────────────────────────────────  β”‚
β”‚  βœ“ Same input β†’ Same output         β”‚
β”‚  βœ“ No side effects during render    β”‚
β”‚  βœ“ Never mutate props or state      β”‚
β”‚  βœ“ Use useEffect for side effects   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

You’ve got this! πŸš€ Keep your components pure, and your React app will be fast, predictable, and bug-free!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.