Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
A pure function is like a reliable calculator. Give it the same input, and it always returns the same output. It doesn't change anything outside itself, and it doesn't depend on anything that might change. React components should work the same way!
Same input = Same output ✅
Changes external variable ❌
Given the same props, this component always renders the same result
function Recipe({ name, ingredients, servings }) {
// Pure! Only uses props, no external variables
const multipliedIngredients = ingredients.map(ing => ({
...ing,
amount: ing.amount * servings
}));
return (
<div className="recipe-card">
<h2>{name}</h2>
<p className="servings">Servings: {servings}</p>
<ul>
{multipliedIngredients.map((ing, i) => (
<li key={i}>
{ing.amount} {ing.unit} {ing.name}
</li>
))}
</ul>
</div>
);
}
function App() {
const pancakeIngredients = [
{ name: 'Flour', amount: 1, unit: 'cup' },
{ name: 'Eggs', amount: 2, unit: '' },
{ name: 'Milk', amount: 1, unit: 'cup' }
];
return (
<div className="container">
<Recipe
name="Pancakes 🥞"
ingredients={pancakeIngredients}
servings={2}
/>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);Loading preview...
A component is impure when it has side effects - it changes things that existed before rendering. This includes modifying variables outside the component, changing the DOM directly, or making network requests during render.
Problem: Changes external state during render!
Solution: Pass data through props!
It's totally fine to change variables and arrays that you create during the same render. This is called local mutation. The key is that these variables didn't exist before your component started rendering!
✅ The array was created fresh in this render - safe to change!
React has a special Strict Mode that calls each component twice during development (not in production). If your component is impure, calling it twice will reveal the problem!
Wrap your app to enable checking!
If you need to do something with side effects (update a variable, call an API, modify the DOM), don't do it during render! Instead, use event handlers or the useEffect Hook.
Follow these guidelines to keep your components pure!
A pure component only cares about its props. Given the same props, it always returns the same JSX. It doesn't change anything outside itself.
React can skip rendering pure components when their props haven't changed. Pure components are also easier to test, debug, and optimize!
Keep rendering pure. Put side effects in event handlers or useEffect!