A Pure Function is a function that always:
- Returns the same output for the same input.
- Does not cause side effects (like modifying global variables, DOM, API calls, etc.).
🔹 Characteristics of Pure Functions
- Deterministic → same input → same output.
- No Side Effects → doesn’t modify external state (variables, objects, DOM).
- Immutability → works with copies instead of changing original data.
🔹 Example of Pure Function ✅
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5 (always same)
👉 No matter how many times you call add(2,3), it will always return 5.
🔹 Example of Impure Function ❌
let count = 0;
function increaseCount(num) {
count += num; // modifies external variable (side effect)
return count;
}
console.log(increaseCount(2)); // 2
console.log(increaseCount(2)); // 4 (different output for same input ❌)
👉 Output is different for the same input because it depends on external state (count).
🔹 Pure Functions in React
In React, components should be pure functions:
- They take
propsas input. - Return JSX as output.
- Do not modify props or external state.
✅ Pure React Component Example:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
❌ Impure React Component Example:
let greetingCount = 0;
function Greeting({ name }) {
greetingCount++; // modifies external variable ❌
return <h1>Hello, {name}! Count: {greetingCount}</h1>;
}
🔹 Why Pure Functions are Important?
- Predictable → easy to test & debug.
- Reusable → can be reused without worrying about external state.
- Helps React → React’s reconciliation (diffing) works better with pure functions.
- Performance → works well with memoization (
React.memo,useMemo).
✅ In short for interview:
“A pure function always returns the same output for the same input and does not cause side effects. In React, functional components are designed to be pure — they depend only on props and state, making them predictable and easy to test.”