Fragments And Pure Components In React

Introduction

 
In the previous article, we learned about the components of the React life cycle and how it is used in React. In this article, we will learn about Fragments and Pure Component and its importance in React. 
 

Fragments

 
In React, when returning any element in render() method, multiple elements must be wrapped within the main container. To provide relief from adding a container to add multiple elements, the concept of Fragment was introduced. Inside <React.Fragment>, it is not required to add any parent container. 
 
The concept of Fragment is introduced after React v16 so to use the concept of Fragment, your application must be updated to the React version 16.2  Let us see a code having multiple elements.
 
For example, the below code has multiple elements.
  1. import React,{Component} from '.react';  
  2.   
  3. class Fragments extends Component{  
  4.         render(){  
  5.                 return(  
  6.                         <p>Test</p>  
  7.                         <p>Test 1</p>  
  8.                         <p>Test 2</p>  
  9.                 )  
  10.         }         
  11. }  
Below, it will display the error as JSX must have 1 parent element.
 
Fragments And Pure Component In React
 
Now, let us see the second approach, i.e., adding a comma (,) after each element.
  1. import React,{Component} from '.react';  
  2.   
  3. class Fragments extends Component{  
  4.        render(){  
  5.               return(  
  6.                      <p>Test</p>,  
  7.                      <p>Test 1</p>,  
  8.                      <p>Test 2</p>  
  9.               )  
  10.        }  
  11. }  
The output will be displayed as below.
 
Fragments And Pure Component In React
As you can see, only the last element is displayed among all three elements. If we want to display all 3 elements in the browser, then we need to return array using square brackets [] instead of parenthesis () like below.
  1. import React,{Component} from 'react';  
  2. class Fragments extends Component{  
  3.         render(){  
  4.                 return[  
  5.                         <p>Test</p>,  
  6.                         <p>Test 1</p>,  
  7.                         <p>Test 2</p>  
  8.                 ]  
  9.         }  
  10. }  
  11.   
  12. export default Fragments;  
Now, the output will be displayed as below.
 
Fragments And Pure Component In React
This approach is also used for returning array but this is a non-JSX syntax. So, let's move towards Fragment which is a React concept.
  1. import React,{Component,Fragment} from 'react';  
  2. class Fragments extends Component{  
  3.        render(){  
  4.               return(  
  5.                      <Fragment>  
  6.                             <p>Test</p>  
  7.                             <p>Test 1</p>  
  8.                             <p>Test 2</p>  
  9.                      </Fragment>  
  10.               )  
  11.        }  
  12. }  
  13.   
  14. export default Fragments;  
The output will be displayed as below.
 
Fragments And Pure Component In React
The second syntax for using the fragment to render an array of elements is using <></>,
  1. import React,{Component} from 'react';  
  2.   
  3. class Fragments extends Component{  
  4.         render(){  
  5.                 return(  
  6.                         <>  
  7.                                 <p>Test</p>  
  8.                                 <p>Test 1</p>  
  9.                                 <p>Test 2</p>  
  10.                         </>  
  11.                )  
  12.         }  
  13. }  
  14.   
  15. export default Fragments;  
The output will be displayed the same as above.
 
Fragments And Pure Component In React
While using React.Fragment does not add any HTMLElement to DOM, the React.Fragment node is added as a parent tag to JSX elements without adding any extra element to DOM.
 

Benefits of Fragments

  1. Some css mechanisms like CSS Grid, Flexbox have some special parent-child relationship and adding div in the middle make it difficult to keep the desired layout while extracting logical components.
  2. This provided a faster and use less memory as it does not create any additional node. This gives a benefit when the application is very large and using these fragments prevents creating unnecessary elements.
  3. Improved semantic markup of JSX. Elements of the wrappers are used if required, not because they are forced.
  4. It provides increased render performance and less memory overhead.

Usage of Fragments

 
Return group of Elements
 
Here, fragments can be used for returning a list of elements without having to wrap them in the container or array. This is useful when returning form and text markup, as wrapping those in a div can cause issues while applying styles.
 
As per the below code, we have defined input text and button.
  1. import React,{Component,Fragment} from 'react';  
  2.   
  3. class Fragments extends Component{  
  4.         constructor(props){  
  5.         super(props);  
  6.                 this.state={  
  7.                         UserName : ''  
  8.                 }  
  9.         }  
  10.   
  11.         render(){  
  12.                 return(  
  13.                         <Fragment>  
  14.                                 <label>Name : </label>   
  15.                                 <input type='text' name='txtuser' id='textuser' value={this.UserName}/>  
  16.                                 <button> Click Me !</button>  
  17.                         </Fragment>  
  18.                 )  
  19.         }  
  20. }  
  21.   
  22. export default Fragments;  
The output is displayed as below.
 
Fragments And Pure Component In React
Conditionally rendering groups of Elements
 
Fragments allow conditional rendering of elements without having to add additional markup tags. We can use ternary or case statements in Fragment to display output in the browser. Let’s look at the example below.
  1. import React,{Component,Fragment} from 'react';  
  2.   
  3. const info = {  
  4.         color: 'blue',  
  5.         fontWeight: 'bold',  
  6.         padding: '4px'  
  7. }  
  8.   
  9. const error = {  
  10.         color: 'red',  
  11.         fontWeight: 'bold',  
  12.         padding: '4px'  
  13. }  
  14.   
  15. class Fragments extends Component{  
  16.         constructor(props){  
  17.                 super(props);  
  18.                 this.state={   
  19.                         UserName : "",  
  20.                         isClicked : false  
  21.                 }  
  22.                 this.handleSubmit = this.handleSubmit.bind(this);  
  23.                 this.handleInput = this.handleInput.bind(this);  
  24.         }  
  25.   
  26.         handleSubmit(){  
  27.                 this.setState({  
  28.                         isClicked :true  
  29.                 });  
  30.         }  
  31.   
  32.         handleInput(e){  
  33.                 this.setState({  
  34.                         UserName: e.target.value  
  35.                 })  
  36.         }  
  37.   
  38.         render(){   
  39.                 return(  
  40.                         <Fragment>  
  41.                                 <label>Name : </label>   
  42.                                 <input type='text' name='txtuser' id='textuser' value={this.state.UserName} onChange={this.handleInput}/>  
  43.                                 <button onClick={this.handleSubmit}> Click Me !</button><br/>  
  44.                                 {this.state.isClicked ? (   
  45.                                         <p style={info}>You clicked button, your name is <b>{this.state.UserName}</b></p>   
  46.                                 ):(   
  47.                                         <p style={error}>Please Click button</p>   
  48. )}   
  49.                        </Fragment>  
  50.                 )  
  51.         }  
  52. }  
  53.   
  54. export default Fragments;  
The output will be displayed as below.
 
Fragments And Pure Component In React 
Fragments And Pure Component In React
Fragments with arrays
 
React provides Fragments concept to use instead of arrays.
 
Using Fragment has the below benefits,
  • When using arrays, children must be separated by comma -- the same case doesn't exist with Fragments.
  • An array needs a key to prevent React key; the same case does not exist with Fragments.
  • In Array, the string must be quoted in double quotations while in fragments it doesn't include such quotes
For example, to define the array, we have the below code.
  1. return[  
  2.       "This is my React Application.",  
  3.       <h2 key="heading-1">Include Introduction</h2>,  
  4.       "Now moving towards.",  
  5.       <h2 key="heading-2">The Complex chapters </h2>,  
  6.       "And provide practical session."  
  7. ];  
 Now, update the codes for Fragments as below.
  1. render(){   
  2.      return(  
  3.           <Fragment>  
  4.                This is my React Application  
  5.                <h2>Include Introduction</h2>  
  6.                Now moving towards  
  7.                <h2>The Complex chapters </h2>  
  8.                And provide practical session  
  9.            </Fragment>  
  10.        );  
  11. }  
Pure Component
 
In React, a component is stated as pure only when it renders the same output for the same state and props and its return value is always the same for the same input values. Component extends React.PureComponent base class is treated as a pure component.
 
Pure Component includes some performance improvements and renders optimization as React implements the shouldComponentUpdate() method for shallow comparison for props and state.
 
Pure Component’s shouldComponentUpdate() method only compares the objects shallowly. In the case of using complex data structures, it can generate false negatives for deeper differences. When you are having simple props and state or use of forceUpdate() you can use this approach or you can use an immutable object incase of deep comparison of data.
 
When PureComponent uses shouldComponentUpdate() method, it skips props updates for the entire component subtree. So when using it make sure all children are pure.
 
For Example, in the case of React.Component
  1. import React from 'react';  
  2.   
  3. class Calculation extends React.Component{  
  4.         constructor(props){  
  5.                 super(props);  
  6.                 this.state={  
  7.                         firstName : "",  
  8.                         fullName:""  
  9.                 }  
  10.                 this.handleFirstName = this.handleFirstName.bind(this);   
  11.                 this.handleClick = this.handleClick.bind(this);  
  12.         }  
  13.   
  14.         handleFirstName(e){  
  15.                 this.setState({  
  16.                         firstName : e.target.value  
  17.                 });   
  18.         }  
  19.   
  20.         handleClick(e){  
  21.                 this.setState({  
  22.                         fullName : this.state.firstName  
  23.                 });  
  24.         }  
  25.   
  26.         render(){  
  27.                 console.log('rendered' + this.state.fullName);  
  28.                 return(  
  29.                         <div>  
  30.                                 <input type="text" value={this.state.firstName} placeholder="First Name" onChange={this.handleFirstName}></input>   
  31.                                 <button onClick={this.handleClick}>Click Me!</button>  
  32.                                 <p> {this.state.fullName}</p>  
  33.                         </div>  
  34.                 )  
  35.         }  
  36. }  
  37.   
  38. export default Calculation;  
The output will be displayed as below.
 
Fragments And Pure Component In React
 
The above output in the console calls the render method each time a button is clicked even if no changes are made in the textbox.
 
Now, update the React.Component to React.PureComponent 
  1. import React from 'react';  
  2.   
  3. class Calculation extends React.PureComponent{  
  4.        constructor(props){  
  5.               super(props);  
  6.               this.state={  
  7.                      firstName : "",  
  8.                      fullName:""  
  9.               }  
  10.               this.handleFirstName = this.handleFirstName.bind(this);   
  11.               this.handleClick = this.handleClick.bind(this);  
  12.        }  
  13.   
  14.        handleFirstName(e){  
  15.               this.setState({  
  16.                      firstName : e.target.value  
  17.               });   
  18.        }  
  19.   
  20.        handleClick(e){  
  21.               this.setState({  
  22.                      fullName : this.state.firstName  
  23.               });  
  24.        }  
  25.   
  26.        render(){  
  27.               console.log('rendered' + this.state.fullName);  
  28.               return(  
  29.                      <div>  
  30.                             <input type="text" value={this.state.firstName} placeholder="First Name" onChange={this.handleFirstName}></input>   
  31.                             <button onClick={this.handleClick}>Click Me!</button>  
  32.                             <p> {this.state.fullName}</p>  
  33.                      </div>  
  34.               )  
  35.        }  
  36. }  
  37.   
  38. export default Calculation;  
Now, observe the output below.
 
Fragments And Pure Component In React
 
Now review the console, if there are no changes made in the textbox then on click of button render method is not called every time.
 

Shallow Comparison

 
The term Shallow comparison is important when using Pure Component. Shallow Comparison refers to 2 primitive types, Primitive Type and Complex type,
 
Primitive Type
 
In Primitive Type, for example we have 2 values, a and b of any type, like strings, boolean or numbers. A shallow comparison b returns true if both are of the same type and have the same value
 
Example, 
  1. let a = “Test”;  
  2. let b = “Test”;  
  3. console.log(a===b); // return true;  
Complex Type
 
In complex type like arrays & object, a shallow comparison b returns true if both have the same objects
 
Example,
  1. let a = {1,2,3}  
  2. let b = {1,2,3}  
  3. let c = a  
  4. console.log(a===b); // return false; point to different object  
  5. console.log(a===c); // return true, as it points to the same object  
Key points to remember while using Pure Component:
  • If parent class is extending PureComponent then we must ensure that child class is also pure to avoid unexpected behavior.
  • Always remember to never mutate the state, in state always returns a new object that is reflecting the new state.
  • Pure Component will not be re-rendered if there is no change in props and state.
  • Pure Component should be used with small applications.

Summary

 
In this article, we learned about Fragment and Pure Component with its usage in React. Also, we reviewed the concept of Shallow comparison. In the next article, we will learn about memo which is a functional component and how it differs from the pure component. And the concept of Refs in React.
 
Next in this series >> Memo and Ref in React
Author
Priyanka Jain
0 9.6k 875k
Next » Portal And Error Boundaries In React