Creating Pure Functional Component using React Memo

How to create Pure Component in React?

A functional component that we are modifying as Pure component:-

import React from 'react';
import Tabs from '../Tabs';
import  './RightPanel.scss';


const RightPanel = () => (
    <div className="rightPanelCta">
        <div className="tab">
            <Tabs>
                <div header="Index.jsx">
                    You are on Index.jsx file
                </div>
                <div header="Panel.jsx">
                    You are on Panel.jsx file
                </div>
            </Tabs>
        </div>
    </div>
);

export default RightPanel;

Option1) This is the traditional approach(Using PureComponent) where you have to create a “Stateful” component even though you need a “stateless” component.

Sample code where we are using Class component, when though we could have used functional component.

class RightPanel extends PureComponent {
    render() {
        return (
            <div className="rightPanelCta">
            <div className="tab">
                <Tabs>
                    <div header="Index.jsx">
                        You are on Index.jsx file
                    </div>
                    <div header="Panel.jsx">
                        You are on Panel.jsx file
                    </div>
                </Tabs>
            </div>
        </div>
        );
    }
}

export default RightPanel;

Option2) Modern approach from React 16.6, using memo API

React.memo(…) is to functional components whatReact.PureComponent is to class components

import React, {memo} from 'react';
import Tabs from '../Tabs';
import  './RightPanel.scss';


const RightPanel = () => (
    <div className="rightPanelCta">
        <div className="tab">
            <Tabs>
                <div header="Index.jsx">
                    You are on Index.jsx file
                </div>
                <div header="Panel.jsx">
                    You are on Panel.jsx file
                </div>
            </Tabs>
        </div>
    </div>
);

export default memo(RightPanel);

If you look at the people in your circle and don’t get inspired, you don’t have a circle, you have CAGE…

Leave a Reply

Your email address will not be published. Required fields are marked *