Higher Order Components

Re-using Component Logic

A React pattern for reusing component logic easily. As a definition, a higher-order component is a function which takes a component and returns a new one. There are some rather popular examples of higher-order components for example Redux's connect(), or "draggable" component libraries such as react-draggable. Below is a simple example of a higher order component; just a component which has a count state.

Times clicked: 0

const InteractableParagraph = withInteractable(Paragraph)

Here we have a component, which doesn't really have much use out of this example. We wrap a component with some onClick functionality, and display a simple counter.

import { useState } from 'react' const withInteractable = (WrappedComponent) => ({ children }) => { const [count, setCount] = useState(0) const handleClick = () => { setCount(count + 1) } return ( <> <span>Times clicked: {count}</span> <div style={{ cursor: 'pointer' }} onClick={handleClick}> <WrappedComponent>{children}</WrappedComponent> </div> </> ) } export default withInteractable

We can use this higher order component by doing the following:

import withInteractable from '../helpers/withInteractable' import { Paragraph } from 'components' const InteractableParagraph = withInteractable(Paragraph) <InteractableParagraph> <CodeSnippit code="const InteractableParagraph = withInteractable(Paragraph)" displayInline /> </InteractableParagraph>