Many of the legacy React projects use class components. This makes using the hooks concept that was released in React v16.8 very difficult, since they are only compatible with React Functional Components.
I encountered one such case while upgrading the react-router dependency from v4 to v5. Since v5 recommends the use of hooks like useLocation()
, useParams()
, etc. I migrated the code using react higher-order components that allow wrapped components to use any (yes, even hooks) function as an injected prop.
Here’s a simple approach to using hooks:
Higher Order Components:
A higher-order component (HOC) is a function that takes a component as an argument and returns a new component that wraps the original component. HOCs are an advanced technique in React for reusing component logic. They are not part of the React API, but rather a pattern that emerges from React’s compositional nature.
HOCs allow you to reuse component logic across multiple components. For example, memo
is a higher-order component that memoizes an entire functional component.
The syntax for an HOC is:
- Function creation:
- `function add (a, b) { return a + b. }`
function higherOrder(a, addReference) { return addReference(a, 20) }
- Function call
How do we create such a HOC for react-router-dom?
We can create a HOC with the following code inside it.
Then, wrap your class components using this HOC like export withRouteProps(yourClassComponent);
After doing all this, you can use these props like props.params
, or props.search
, etc.