Intro to ReactJS basic - Part 1 βοΈβοΈβοΈ
React JS Virtual DOM Explained - Part 2 π²π²π²
Advance React Hooks - Part 3π―π―π―
React Context Guide - Part 4 πππ
ReactJS Explained Hooks - Part 5 β‘οΈβ‘οΈβ‘οΈ
In React, Pure Components are a type of component that optimizes performance by preventing unnecessary re-renders. A Pure Component is essentially a component that implements a shallow comparison of its props and state to determine if it should re-render. If the props and state haven't changed, the component will not re-render, which can enhance performance, especially in applications with many components.
Key Features of Pure Components
Shallow Comparison:
- Pure Components perform a shallow comparison of props and state. This means that React checks if the previous and current props and state references are the same. If they are, it skips re-rendering the component.
Inherits from
React.PureComponent
:- Pure Components are created by extending
React.PureComponent
. They behave similarly to regular class components but come with the additional optimization of shallow prop and state comparison.
- Pure Components are created by extending
Functional Equivalent:
- Functional components can achieve similar optimization by using
React.memo
, which wraps a functional component to prevent re-renders when props haven't changed.
- Functional components can achieve similar optimization by using
When to Use Pure Components
Performance Optimization: Use Pure Components when you have components that receive the same props frequently and only need to re-render when their props or state change.
Component Hierarchies: They are particularly useful in complex component trees where deep nested components might be affected by parent state changes but don't necessarily need to update.
Example of a Pure Component
Hereβs a simple example illustrating the use of a Pure Component:
javascriptCopy codeimport React from 'react';
// Creating a Pure Component
class MyPureComponent extends React.PureComponent {
render() {
console.log('Rendering MyPureComponent');
return <div>{this.props.value}</div>;
}
}
// Parent Component
class App extends React.Component {
state = {
count: 0,
value: 'Hello, World!',
};
incrementCount = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};
changeValue = () => {
this.setState({ value: 'Hello, React!' });
};
render() {
return (
<div>
<MyPureComponent value={this.state.value} />
<button onClick={this.incrementCount}>Increment Count</button>
<button onClick={this.changeValue}>Change Value</button>
<p>Count: {this.state.count}</p>
</div>
);
}
}
export default App;
Explanation of the Example
Pure Component:
MyPureComponent
extendsReact.PureComponent
. It will only re-render if itsvalue
prop changes.Parent Component: The
App
component maintains a state withcount
andvalue
.Incrementing Count: When you click the "Increment Count" button, only the
count
state changes. However,MyPureComponent
does not re-render because itsvalue
prop remains the same.Changing Value: When you click the "Change Value" button, the
value
prop changes, causingMyPureComponent
to re-render.
Benefits of Using Pure Components
Performance Improvement: By preventing unnecessary re-renders, Pure Components can lead to significant performance improvements in applications, especially those with complex component trees.
Simpler Code: Since Pure Components handle their own re-rendering logic, they can reduce the need for manual optimizations throughout your application.
Caveats
Shallow Comparison Limitations: Pure Components only do a shallow comparison. If you pass objects or arrays as props, changes to their contents (not the references) will not trigger a re-render. You need to create new references for objects or arrays if they change.
Overhead of Comparison: In cases where the props are complex and change frequently, the overhead of shallow comparison might outweigh the benefits. In such cases, regular components with manual optimizations may be preferable.
State Management: If a component relies on complex state management (like deeply nested objects), using Pure Components can complicate the logic needed to ensure proper updates.
Conclusion
Pure Components are a powerful optimization tool in React that can help improve performance by minimizing unnecessary re-renders. They work well when props and state are stable and only change under specific conditions. However, developers should be mindful of their limitations and ensure they use them appropriately based on their application's needs.
Introduction pure function π
A pure function is a concept from functional programming that refers to a function with specific characteristics that make it predictable, testable, and maintainable. In the context of programming, particularly in JavaScript and React, pure functions are essential for creating reliable and side-effect-free code.
Characteristics of Pure Functions
Deterministic:
- A pure function always produces the same output for the same input. Given the same arguments, it will always return the same result without any variation.
Example:
javascriptCopy codefunction add(a, b) {
return a + b;
}
// add(2, 3) will always return 5
No Side Effects:
- A pure function does not cause any observable side effects outside of its scope. This means it does not modify any external state, perform I/O operations, or change the values of its input parameters.
Example:
javascriptCopy codelet count = 0;
function incrementCount() {
count += 1; // This function has a side effect
}
Referential Transparency:
- Pure functions can be replaced with their output values without changing the program's behavior. This property allows for easier reasoning about the code and optimization by compilers.
Example:
javascriptCopy codeconst result = add(2, 3);
// Wherever add(2, 3) appears, it can be replaced with 5 without affecting program behavior.
Benefits of Pure Functions
Easier Testing:
- Pure functions are straightforward to test since their output depends only on the input parameters. You can create unit tests that check various input cases without worrying about external state.
Example:
javascriptCopy codeconsole.assert(add(2, 3) === 5);
console.assert(add(-1, 1) === 0);
Predictability:
- Because pure functions have no side effects, they are predictable and easier to reason about. This predictability makes them ideal for functional programming and reducing bugs.
Improved Maintainability:
- Code that relies on pure functions tends to be more modular and easier to maintain. Changes in one part of the code are less likely to affect unrelated parts.
Facilitates Functional Programming Techniques:
- Pure functions are a cornerstone of functional programming paradigms, enabling techniques like function composition, higher-order functions, and immutability.
Examples of Pure Functions
Example 1: A Pure Function
javascriptCopy codefunction multiply(a, b) {
return a * b; // Deterministic and has no side effects
}
Example 2: An Impure Function
javascriptCopy codelet externalValue = 10;
function addExternalValue(x) {
return x + externalValue; // Uses external state, thus impure
}
Using Pure Functions in React
In the context of React, pure functions are often used for rendering UI components, calculating derived state, and managing state transitions. Using pure functions in your React components can enhance performance and maintainability.
Pure Component Example:
javascriptCopy codefunction Greeting({ name }) { return <h1>Hello, {name}!</h1>; // Pure function; no side effects }
State Calculation:
javascriptCopy codefunction calculateTotalPrice(items) { return items.reduce((total, item) => total + item.price, 0); // Pure function }
Summary
Pure functions are functions that consistently produce the same output for the same inputs and do not have side effects.
They promote better testing, predictability, and maintainability in your code.
Pure functions are essential in functional programming and are widely used in React for rendering components and managing state.