In react, HOCS and Render Props have common goals but different implementations. The main purpose of a higher-order component in React is to share common functionality between components without repeating code. Render Prop is also a technique for sharing code between React components using a prop whose value is a function.
Here are the definition and screenshots below,
HOC's
HOC is an advanced technique for reusing component logic. It is a function that takes a component and returns a new component.
RenderProps
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic
#App.js
import React from "react";
import "./style.css";
import Welcome from './Welcome';
import Location from './Location';
export default function App() {
return (
<div>
<h2 style={{color: "red"}}>Highorder example</h2>
<Welcome/>
---------------------------------------------
<h2 style={{color: "red"}}>RenderProps example</h2>
<Location/>
</div>
);
}
#Hoc.js
import React from 'react';
import ReactDOM from 'react-dom';
function Hoc(Component) {
const user = 'Hi User';
return function () {
return <Component user={user} />
};
}
export default Hoc;
#Welcome.js
import React from 'react';
import MyHoc from "./HocExample";
const Welcome = ({ user }) => {
return (
<>
<h1> {user} </h1>
<h1 style={{ color: "green" }}>Welcome to CDK Global</h1>
</>
);
}
export default MyHoc(Welcome);
#RenderPropExample.js
import React from 'react';
import ReactDOM from 'react-dom';
function RenderPropExample(props) {
const city = "Hyderabad";
const location = <h1>Location</h1>
return props.children({
location: location,
city: city
})
}
export default RenderPropExample;
#Location
import React from 'react';
import Renderprop from "./RenderPropExample";
const Location = () => {
return (
<>
<Renderprop>
{({ location, city }) => {
return (
<>
<h3>{location} </h3>
<h1 style={{ color: "green" }}>{city} </h1>
</>
)
}
}
</Renderprop>
</>
);
}
export default Location;
Output
https://react-279yzk.stackblitz.io