What is the difference between HOC and lifting state up in ReactJS?

Viewed 350

What is the difference between HOC and lifting state up in ReactJS? In both methods we can share state what is difference?

2 Answers

Higher order components generates new component based on a shared behavior, while lifting state up moves the state management to a parent or an ancestor component.

If a state is managed by a higher order component, it will not be shared by the component it wraps. For example with the following:

const useTemperature = (WrappedComponent) => {
  return (props) => {
    const [temp, setTemp] = useState(0);
    return <WrappedComponent {...props} temp={temp} setTemp={setTemp} />
  }
}

When you create the component useTemperature(Celcius) and useTemperature(Farenheit) the state of those two is still separate.

If a state is managed by lifting state up, it will be shared by child components. For example if you have the following:

const Temperature = () => {
  const [temp, setTemp] = useState(0);
  return (
    <>
      <Celcius temp={temp} setTemp={setTemp} />
      <Farenheit temp={temp} setTemp={setTemp} />
    </>
  );
}

Calling setTemp in Celcius will change temp in Farenheit and vice versa.

HOC and lifting the state up are two different things.

HOC is a component which can return the same component but with additional props and features. The HOC takes one component as an argument and it returns the same component.

class Parent extends React.Component {
    constructor(){
       this.state = { name: "Parent" }
    }

    render(){
       return (
         <button>{this.state.name}</button>
       );
    }
}

const hocComp = (wrappedComponent) => {
    // some other features you can create here.
    return () => <wrappedComponent />
}

Lifting the state is a technique where you can share state object updates to several other components. In this technique one declares a state object at the parent class and exposes one method to child component and passes as a prop to update the state via setState.

class Parent extends React.Component {
    constructor(props){
       super(props);
       this.state = { name: "Parent" }; // <---lifted state in parent
       this.updateName = this.updateName.bind(this);
    }

    updateName(name){ // <-----method to update the state
       this.setState({name});
    }

    render(){
       return (
         <button>{this.state.name}</button>
         <Child onUpdateName={this.updateName} /> //<---pass one method to child
       );
    }
}

const Child = props => {
   const onUpdateName = () => {
      props.onUpdateName('Child'); //<-----trigger this to update parent's state
   }
   return(
      <button onClick={onUpdateName}>Child</button>
   );
};

Lifting the state would be very cumbersome when your application grows that is where context api or redux will be used for the same.

Related