I was referring to the below link (section : HOCs for Functional Components)
https://rossbulat.medium.com/how-to-use-react-higher-order-components-c0be6821eb6c
In the example, below is the code for the HOC;
//functional HOC with useState hook
import React, { useState } from 'react';
function withCountState(Wrapped) {
return function (props) {
const [count, setCount] = useState(0);
props['count'] = count;
props['setCount'] = setCount;
return <Wrapped {...props} />;
}
}
Also, the Wrapped component code is as below;
const Wrapped = (props) => {
const {count, setCount} = props;
return(
<div>
<h1>Counter Functional Component</h1>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Increment count
</button>
</div>);
};
For applying HOC to , we use
const EnhancedWrapped = withCountState(Wrapped);
Now I have 2 questions;
- For consuming this component, do we just say
<EnhancedWrapped>
may be in our App.js or do we need anything else?
- What benefit do we really get out of creating this HOC?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…