Reputation: 50742
React HOCs are said to be pure functions. But don't we add some props to the original/base component and return a new enhanced component ? So with this "adding" of props, how are HOCs still considered pure functions ?
Upvotes: 1
Views: 745
Reputation: 1055
An HOC is a pure function because it has no side effects. From the docs:
Note that a HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side-effects.
A thing that I think seems a bit off about this way of thinking about an HOC is that props are being added to the input component. The input component is being provided with new props it could already accept, nothing about the component itself is being changed.
I keep coming back to this answer because I feel like a lot can be said about it, but think about a higher order function:
const higherOrderFunction = (pureFunc) => {
const x = someWorkWithoutSideEffects;
return pureFunc(x);
}
We would say that higherOrderFunction
is not only a higher order function, but also that it is a pure function, right? I think that this is pretty well analogous to exactly what an HOC is doing.
Upvotes: 3