user117829
user117829

Reputation: 566

Are the components returned from higher-order components called closures?

I have a higher-order component FormBuilder like this:

const FormBuilder = (WrappedComponent) => {
  const name = 'bob';

  return class HOC extends React.Component {
    render() {
      return (
        <div> 
          <WrappedComponent {...props} />
        </div>
      );
    }
  }
}

I am thinking that the HOC component that is being returned from this function can be thought of as a closure because it has access to its props(own scope), variable name and component WrappedComponent(outer function's scope) as well as anything defined in the global scope. Anyone can verify whether my thinking is right?

Upvotes: 1

Views: 1052

Answers (1)

Ashish
Ashish

Reputation: 11

Yes component return from higher level component (HOC) can be treated as closure. With the help of closure we can maintain state by storing value in a variable which can be accessible by inner function. In case of higher order component as well we can maintain state by defining state at higher level component and can pass that state to low level component and by calling event function on props we can send data back to Higher Order Component.

Difference: In case of closure we don't have a control on conditional rendering. If we want to render only child component we can easily do in case of higher order component by ShouldComponentUpdate() life cycle method but we can't do in closure. In case of closure function2, function3, function4 have access to variable x

function1(){
  var x = 4;
    return function2(){
      return function3(){
      return function4(){
      }
      }
      }
      }

In case of higher order component we have a control on what data to send to lower component. We can make x available to function1 and function2 by sending as props but we have option not to send to function3 as well as function4. In this way we can have more control in case of higher order component. All the component will have there own copy of x variable.

Upvotes: 1

Related Questions