Why are higher-order components much more useful than usual?

I don't seem to understand the understanding of why higher order components are highly valued over regular components? I read a tutorial on them and that higher-order components are good because they: 1) Allow code reuse, logical and boot abstraction. 2) They are able to render. 3) The ability to abstract state and manipulate them. 4) The ability to manipulate props. Source: Link

An example of a higher order component in the code was shown there as:

function refsHOC(WrappedComponent) {
  return class RefsHOC extends React.Component {
    proc(wrappedComponentInstance) {
      wrappedComponentInstance.method()
    }

    render() {
      const props = Object.assign({}, this.props, {ref: this.proc.bind(this)})
      return <WrappedComponent {...props}/>
    }
  }
}

They look almost exactly the same as the definition of a regular class that gets the details, and you can still "manipulate the details" and "manipulate the state" inside this class

class Something extends React.Component {
  constructor(props) {
    super(props);
    this.state = { food: 'no_food_received_yet' } 
  }
  componentDidMount() {
    this.setState({ food: 'apple' });
  }
  render() {
    return (
      <div>
       <p>{ this.state.food }</p>
       <h2>{ this.props.food }</h2>
      </div>
    );
  }
}

, , .

bash - . , , -.

+4
3

HOC , , " ".

:

let Button = props => <button style={{ color: props.color }} />

BlueButton:

let BlueButton = props => <Button color="blue" />

, , , , , . HOC, "" :

let blueify = Component => props => <Component {...props} style={{ color: 'blue' }} />

, divs, !

let BlueButton = blueify(Button)
let BlueDiv = blueify(props => <div {...props} />)
+3

, , . , 3 . , , , , , , . , 3 . HOC , HOC, , . , HOC.

+1

, . ( ) .

. () HTML. 101; , PI, , , 3.14159, .

A simple example of a “higher order component” (in this case, a higher order function) is a sort function, which takes an order function as one of its arguments. By allowing you to manage your order using an external function, you can change the sort behavior without changing the sort function itself.

+1
source

Source: https://habr.com/ru/post/1680509/


All Articles