Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - Usage of React HOC for Functional Components

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;

  1. For consuming this component, do we just say <EnhancedWrapped> may be in our App.js or do we need anything else?
  2. What benefit do we really get out of creating this HOC?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. For consuming this component, do we just say may be in our App.js or do we need anything else? Yes, just use HOC like any other JSX component.

  2. What benefit do we really get out of creating this HOC? You can make it reusable. Let's say you want another component with different content inside, like , you could just create a new component by const AnotherEnhancedWrapped = withCountState(AnotherWrapped);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...