Hello React Friends,
In this article, we will go through the ReactJS HOC concept, why to use them, and how to use them in ReactJS with an example.
So let’s get started with ReactJS Higher-Order Components.
Contents
Higher-order components or HOC is the advanced method of reusing the component functionality logic in the project. It simply takes the original component and returns the enhanced component. HOC uses the DRY (don’t-repeat-yourself) programming principle, which is very important while building an application or writing code.
const EnhancedComponent = higherOrderComponent(OriginalComponent);
import React, { useState } from 'react' const HOC = (OriginalComponent)=>{ function NewComponent () { const [Value, setValue] = useState(0) const handleClick = () =>{ console.log(2) setValue(Value + 2) } return <OriginalComponent handleClick={handleClick} Value={Value} /> } return NewComponent } export default HOC import React, { useState } from 'react' import HOC from './HOC' const Person1 = ({Value, handleClick}) => { return ( <> <div>Person1: {Value}</div> <button onClick={()=> handleClick()}> Count number </button> </> ) } export default HOC(Person1) import React from 'react' import HOC from './HOC' const Person2 = ({handleClick, Value}) => { return ( <> <div>Person2 : {Value}</div> <button onClick={()=> handleClick()}> Count number </button> </> ) } export default HOC(Person2)
Hence, this was all about Higher-Order Components in ReactJS. If you face any difficulty, kindly share it with me through the comment box. Connect with ReactJs Developers and learn more.
Spread the tutorial with your friends to help them learn about Higher Order Components in ReactJS.
Happy Coding!
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…
The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…
Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…
Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…