React HOCs

HOCs

A higher-order component (HOC) is an advanced element for reusing logic in React components. Components take one or more components as arguments, and return a new upgraded component.

facts about HOCs:

  1. We don’t modify or mutate components. We create new ones.

  2. A HOC is used to compose components for code reuse.

  3. A HOC is a pure function. It has no side effects, returning only a new component.

examples of HOCs:

react-redux

connect(mapStateToProps, mapDispatchToProps)(UserPage)

react-router

withRouter(UserPage)

material-ui

withStyles(styles)(UserPage)

Use Cases:

  • Show a loader while a component waits for data

  • CONDITIONALLY RENDER COMPONENTS

  • PROVIDE COMPONENTS WITH SPECIFIC STYLING

  • PROVIDE A COMPONENT WITH ANY PROP YOU WANT

Hooks vs HOCs

HOCs Pros:

  • Easily separate all logic from the UI component (see recompose).

  • Easy to compose.

  • Manipulate component before any render.

HOCs Cons:

  • Name clashes - 2 HOCs can use and set a prop with the same name.

  • React dom is gigantic.

  • Every change in the parent props caused the children to rerender - which is the default behavior in React but when we have many HOCs we need to be very careful.

  • Types - From the component point of view, it is difficult to understand which props and types we are getting.

  • Using a HOC will pass all the props to the child, even if the child needs from that specific HOC only the prop x.

  • The process of using an argument that depends on a component's props for the HOC can be complicated

HOCs Pro & Con both:

  • No need to define variables, just wrap with a HOC and you'll get the props the HOC supplying - which makes our UI component "guess" the names of the props.

Hooks Pros:

  • Readable & declarative.

  • Performance - updates only when specific props are changed.

  • Growing community.

Hooks Cons:

  • Only within the component - which means cannot render component by a condition of props that are passed.

  • Giant component files which contain UI & logic altogether.

As a rule of thumb, use HOCs when you want a conditional rendering of components (if condition: render A, else render B), otherwise, I use hooks.

Last updated

Was this helpful?