0

I'm wondering if there's a pattern that allows me to prevent an HOC from recalculating based on some condition, here's an example:

const DumbComponent = () => <button>Click me<button/>;

// Third party HOC, that I can't modify
const SmartComponent = Component => class extends Component {
  componentWillReceiveProps() {
    // Complex stuff that only depends on one or 2 props
    this.state.math = doExpensiveMath(props);
  }
  
  render() {
    return <Component {...this.props} math={this.state.math} />;
  }
}

const FinalComponent = SmartComponent(DumbComponent);

What I'm looking for, is a pattern that prevents this HOC from doing its thing if the props I know it depends on haven't changed. But that doesn't stop the entire tree from rerendering based on props like shouldComponentUpdate would do.

The catch is, that this HOC comes from another library and ideally I don't want to fork it.

Florian Bienefelt
  • 1,448
  • 5
  • 15
  • 28
  • It's hard without knowing what the `SmartComponent` is doing but if it's just computation then you should `Memoize` the props you pass to it in a key (maybe hash the props) value obj and render directly the child component in that case. – Yassine S. May 03 '19 at 09:27

1 Answers1

0

What i got is you want to prevent hoc to recompute certain logic for that you can do as below :-

const DumbComponent = () => <button>Click me<button/>;

// Third party HOC
const SmartComponent = Component => class extends Component {
  componentWillReceiveProps() {
    // Complex stuff that only depends on one or 2 props
    this.state.math = doExpensiveMath(props);
  }

  render() {
    return <Component {...this.props} math={this.state.math} />;
  }
}

const withHoc = SmartComponent(DumbComponent);
class FinalComponent extends Component { 
    render() {
        if (your condition here) { 
            return (
                <withHoc {...this.props} />
            ); 
        }

        else {
            return <DumbComponent {...this.props}/>;
        }
    }
}

export default FinalComponent; 
Codesingh
  • 3,316
  • 1
  • 11
  • 18