1

Suppose we have a HOC withWidth and a hook useWidth which both injects the current window width as a prop in a component.

withWidth:

const MyFunctionComponent = withWidth(({width}) => {
  return width === 'mobile'
    ? // render mobile version
    : // render desktop version
});

useWidth:

const MyFunctionComponent = () => {
  const width = useWidth();

  return width === 'mobile'
    ? // render mobile version
    : // render desktop version
};

What are the pros and cons both patterns? When should I prefer the one over the other?

The withWidth HOC solution isn't better at a Dependency Inversion Principle perspective? It's easier to mock the width dependency and to write tests, and the component itself doesn't have to handle the width creation.

And if it is, why we prioritize the usage of hooks? At least I often see this approach, prioritizing the usage of hooks instead of HOCs when possible.

I'm still learning about concepts of Dependency Inversion and stuff. These concepts often are examplified using Java, so transposing to JS and React world is quite difficult to me.

Steven
  • 166,672
  • 24
  • 332
  • 435
Edu Paz
  • 143
  • 1
  • 7

0 Answers0