1. What is HOC (Higher-Order-Component)?

A Higher Order Component (HOC) is a component that is a wrapper for another component. It allows you to create i.e. common properties for several components, standardize props passed to them or perform operations before rendering the component.

In fact, it is a function that takes component A as an argument. This function returns another component B, which performs operations and renders the previously passed component A, enriched with other or modified properties.

This function can be used to declare a new, wrapped component.

interface MyComponentProps { label: string } const MyComponent: FC<MyComponentProps> = ({label}) => { return <>Label: {label}</>; } const requiredComponent = (Component: FC): FC => ({label, ...props}) => { return <Component {...props} label={`${label}*`} />; }; const RequiredComponent = requiredComponent(MyComponent); <RequiredComponent label={"Email"} /> // Label: Email*

In the above example, each component wrapped in requiredComponent will receive an asterisk at the end of the string passed to the label property. A common use of HOC is, for example, adding validation of form component fields or otherwise sharing their mechanics,

HOC can be both functional and class components.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.