React Higher Order Component (HOC)
Hello guys, Today I'm going to explain about Higher Order Components in React,
What is HOC
HOC is a function that gets a Component as an argument and returns another Component instead of JSX, we are using these components to share complex logic and behaviours with more UI components and also to add extra functionalities to components.
// Normal Component
Component => <div>JSX</div>
// HOC
HOC => Component => <div>JSX</div>
Confused😳 Let's see more examples,
// User Component
const User = ({ name }) => <div>Name - {name}</div>
// Let's create a HOC to print props
const withPrintProps = (Component) => {
return (props) => {
console.log(props)
return <Component {...props} />
}
}
// Let's create a User component with print props functionality
const UserWithPrint = withPrintProps(User)
// usage
function App = () => {
return <UserWithPrint name="Dileepa Chandima" />
}
So here what we added is to print the props to the console, But I think now you have a good understanding of how HOC works,
This is a small list of HOC usages,
Add logs to the components (eg: Sentry logs)
Add event tracking for marketing purposes
Redux
connect
is a usage of HOCAdd Data fetching logic according to the props
Subscribe to my newsletter
Read articles from Dileepa Chandima directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Dileepa Chandima
Dileepa Chandima
Experienced and self-motivated software engineer with a Computer Science and Engineering background having 6+ years of experience in Mobile Application and Web Application development. A dynamic personality, and motivated team player with sound leadership skills.