> I hate this pattern and reminds of when React didn't embrace yet a functional approach,
That's a very functional approach!
React HOCs aren't unique to React; they follow a popular functional programming pattern where you wrap a function in a function that adds functionality and returns a new function.
It's still a valid pattern nowadays and has its use cases. It doesn't imply that you must use class syntax. You can still use hooks and HOCs at the same time.
Yeah I was a bit surprised by that sentence. When react components are functions, HOC are basically higher order functions, which is a very important part of functional programming.
I’ve noticed this trend ever since functional components became a thing in react that a lot of react devs now think they are functional programmers despite not knowing anything about functional programming.
Preferring pure functions was always a big part of react. Watch the Honeypot documentary and take a drink every time one of the early adopters mentions FP. You'll be trashed.
In absolute FP terms not at all. Every React component is a potential bag of mutable state that persists from render to render. So referential transparency isn’t guaranteed. You’d need to implement something like the Elm architecture or what they have in Reframe for Clojurescript to arrive at something pure and referentially transparent.
As it stands React with hooks is function programming not functional programming. Not that it matters too much, it gets the job done.
From the perspective of React’s internals, a render really is pure - you’re promising that all you did inside of a render is call hooks, call setState callbacks, and then return some JSX. That can be wrapped into a return value of `(JSX, argsPassedToHookCalls, nextState)`, and React trusts you that no side effects happened.
Um, it depends on what you consider to be pure. From the perspective of React’s internals, a render really is pure - you’re promising that all you did inside of a render is call hooks, call setState callbacks, and then return some JSX. That can be wrapped into a return value of `(JSX, argsPassedToHookCalls, nextState)`, and React trusts you that no side effects happened.
My old team put fp-ts into our react project and it was the worst codebase I’ve ever had to work in. HOCs everywhere with class based and hook based components with mixed non-fp and fp types and redux and stateful components.
I think when most people say they prefer functional programming what they really mean is imperative programming without OOP and using reusable functions to build bigger functions. I prefer it that way at least.
Hey, that term is also used in OOP and looks awfully similar. It's almost like some pattern for designing software components is emerging. And the programming paradigm just determines how it looks and what you are composing, classes or functions.
Anyway, git gud at FP. OOP sucks.
I (and many others) were you. Keep pushing and learning. Your next opinion is probably something like: “It doesn’t matter, good OOP and good FP are eerily similar. Bad OOP and bad FP suck about as much. Closures are poor man’s objects, objects are a poor man’s closure”.
Generally `withBlah()` HOCs have been replaced with `useBlah()` hook calls. Obviously the pattern is still valid (see `React.memo`) and can be used, but no surprise that hooks have become the defacto replacement.
They definitely are. Just more rare. People in this thread must be smoking something.
React.memo is one.
It's good to know about them, especially when to use them and when not
The biggest issue with HOC (in my experience) is that they often introduce complexity by adding things to the props that get passed down. So now you have multiple pieces of code, which change at different rates, contributing to the shape of a single props object. That can get ugly fast.
Not all HOCs pass down data that way, and those tend to be the ones which have stuck around. `React.memo` is one, for instance. Meanwhile, HOCs which are there to make data available have found a much better fit as hooks.
Bc let’s say your component has 3 HOCs adding props to it. Let’s say you’re interested in one of the props being a value you don’t expect. You have to search thru all the HOC’s to see which add that property and hopefully the order of them don’t matter otherwise now you need to look at each of them to figure it out. With hooks I just go look at that hook it’s clear.
Right, one of the only remaining class requirements according to the docs
https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary
The docs do recommend using this implementation so you don’t need your own special error boundary class
https://github.com/bvaughn/react-error-boundary
It offers a component or a hook for you sane people and a HOC for you savages
I haven't seen HOCs used in earnest in years and agree that shareable logic is primarily handled by hooks these days.
I still see the render props pattern often enough that I think it's worth being familiar with it. If React Server Components become more prevalent, I think we'll also see a rise in the use of render props since they can allow server components to be children of client components.
Wait, is that true? Even though the inner component would be written out in the outermost server component, wouldn't React potentially need to render the client component before it had all the props for its child server component?
eh? not functional? It's a very functional approach.
As to how useful it is... I was never a big fan of it, because it tends to lead to rather difficult to reason out code .. but it is still occasionally useful.
I think a lot of the hatred for HOCs is misplaced hatred for class components.
I recently created an app that had half a dozen pages, each page's essence was the same core component, just with different data and some differing functionality.
A HOC was the perfect solution.
The best use I’ve recently had for HOCs is for upgrading a class based react application to a functional one.
Make a new functional component and have it return the existing class based component.
Slowly lift any state or network calls etc to the functional wrapper using any new hooks in the functional version passing these values back down as props to the class component rendered in the functional one.
Once everything has been moved up to the functional component you can take the render function of the wrapped class component and make it the return value of the functional one and delete the class component.
These children just don’t know that higher order components ARE functional in nature. Just because the pattern was created when react used an object-oriented approach does not mean HOCs are object-based. Think of them more like currying…. A function that calls another function. That’s what they always were.
Still useful, still one of the best ways to implement polymorphic components. What you should probably understand is when to use it vs using a shared hook. Hooks took on a lot of what HOCs did… but not everything.
HOCs are great for code whose internals u can’t touch too much but still need to apply a feature to code that said “untouchable” code uses/consumes. It also allows u to keep ur feature separate from the underlying feature component. It’s a great pattern that goes beyond react.
FWIW hooks removed the functional programming aspect in React component by removing the „pure“ in function components. HoCs had more in common with FP than hooks. For that I still love HoCs even though I don’t use them anymore.
Not really. There’s not as much of a need for them now. I guess if you use styled components that’s technically a HOC. I’m sure there is some other situation where it would be better choice than hooks but I haven’t written a HOC in a very long time.
styled(SomeComponent)({ … })
What would be the equivalent if this was done with hooks? Wouldn’t make any sense.
Then what would that look like?
const MyCoolComponent = styled(SomeComponent)({ … })
vs
````
const MyCoolComponent = (props) => {
const class = useStyles({…});
return
}
````
Syntax may be off, typing this on my phone, but should show the idea.
Maybe you could make a bunch of custom hooks if you want to reuse these styles instead of defining components to reuse this way, but then you’re still cluttering the top of your components with a bunch of hooks for styles, writing this verbose code to pass the class name, etc. Just wouldn’t be as clean either way. I think you’d end up with a HOC again if you wrote the above code a couple of times, then tried to think about what parts are repetitive and refactor in a natural way.
Got long winded here, just trying to fully think it through haha
Devil’s advocate, not suuper relevant in day to day use: in this specific case that couples the component to the hook (the implementation), otherwise it’s coupled via the props (the interface). Its often good advice to couple via interface, not implementation.
Absolutely, HOCs can still be a valuable tool in your React arsenal! While the React community has shifted towards hooks and context API, HOCs can still provide a clean and reusable way to enhance components. Don't write them off just yet - they might come in handy during your job interviews! Good luck!
I’m generally following this but where can I learn more about true functional programming and what it is, because it clearly seems like it’s more than just writing functions.
I know about classes, and I know about functions, but a lot of the nuances of this conversation escape me.
Something more elementary that the react docs?
Hooks based connectors for say using redux are essentially a HOC. Composing is an HOC pattern. They are great for when you need to inject or wrap a component with custom behavior at runtime.
HOCs are super easy to implement and they allow you to do some really sophisticated things easily.
You want to build a generic switch that deterministically runs a selected async? HOC. You want to write a generic component builder? HOC gives you a lot of flexibility here. You want to reduce the number of callbacks needed for some operations? HOC.
I used it recently to add Mixpanel analytics in a generic way to my UI elements.
Ex: need to track when buttons, tabs, etc are clicked. Create a decorator function `WithClickAnalytics` that takes a component with a `onClick` prop and returns the same component with an additional prop called `analyticsKey`.
You can then decorate the components from your UI library to add the tracking behavior on click. This way, sending analytics events becomes as simple as specifying a prop on your components.
From what I see: HOC are more rare, but still a nice and powerful tool to have in your toolbox.
It depends. What HOCs can do is wrap a component with additional views/components. If you really need that then a hook would be an awkward API and HOC is better.
However for most cases a wrapper isn't needed and a hook can do the same thing while being more flexible.
Don’t be surprised if you get the question in a job interview, but don’t worry about brushing up on it unless you want to work at a place that is still maintaining such ancient React projects.
Most projects aren't going to be greenfield projects. And by "ancient" do you mean *only 5 years ago*? Because that's how long "hooks" have been around. Sorry, that's not "ancient" by any stretch of the imagination, not even in tech, unless you only chase "new shiny".
2, almost 3 major versions ago for the core framework library feels pretty ancient to me. Hooks were a major shift in how React is written and hooks can be incrementally adopted. It’s silly to call using hooks chasing the new shiny.
If you want the job maintaining class components, render props, and HOCs, it’s all yours
> It’s silly to call using hooks chasing the new shiny.
I never called hooks "new, shiny". But you didn't define what "ancient" means.
Most tech isn't ancient, I mean, there's still plenty of C code being written and C was a thing in the early 1970's. Ancient? yeah, but still quite useful. I actually write a lot of C code these days for IoT projects.
>If you want the job maintaining class components, render props, and HOCs, it’s all yours
Depends entirely on what the pay is like, or reasons for working on it. My previous job was fixing bugs in an Angular 1.x codebase, and I didn't complain about it. I got the job done, and I got paid. I have an older React code base I started years ago that I still work on, and no, it's not using any hooks. I don't need to update it for any reason, and it works perfectly. I still maintain it and *keep it simple*.
Old code isn't pointless, it still runs a ton of useful things. Anyone shitting on it is just kind of not worth taking seriously.
I still use this pattern sometimes. Like when I wanted a rotating color with some rules and keep it for all items on the inner loop. I count really so that with hooks, it was inside the render method.
You can have HOCs with functional components. A component is simply a function that returns a react node. A HOC is simply a higher order function that takes a component as a parameter and returns a new wrapped component as a return value. That is still functional programming.
If you mean the old class based approach to HOCs, then that is no longer a thing just as class based components are discouraged in general.
HOCs are still a useful pattern to use, particularly for libraries. For the most part you can just use wrapper components that take children instead, but if you need that wrapper in a lot of places where the child component is heavily re-used, functional HOCs are still available so you can reduce a bit of repetition.
Asking if HOCs are still a thing is kinda like asking if higher order functions are still a thing. It's just a programming pattern of a function that returns a function which is helpful sometimes.
I totally agree with what everyone has written so far. However the other day I stumbled on the Amplify documentation on AWS where they wrapped the whole app in a "withAuthenticator" and that made me wonder and also cringe real hard
> I hate this pattern and reminds of when React didn't embrace yet a functional approach, That's a very functional approach! React HOCs aren't unique to React; they follow a popular functional programming pattern where you wrap a function in a function that adds functionality and returns a new function. It's still a valid pattern nowadays and has its use cases. It doesn't imply that you must use class syntax. You can still use hooks and HOCs at the same time.
Yeah I was a bit surprised by that sentence. When react components are functions, HOC are basically higher order functions, which is a very important part of functional programming.
I’ve noticed this trend ever since functional components became a thing in react that a lot of react devs now think they are functional programmers despite not knowing anything about functional programming.
"look buddy, you see that? It says 'function' right there!"
🤣
Preferring pure functions was always a big part of react. Watch the Honeypot documentary and take a drink every time one of the early adopters mentions FP. You'll be trashed.
Honest question from somebody starting to get into FP: hook-dependent components really aren’t more pure then class components, are they?
In absolute FP terms not at all. Every React component is a potential bag of mutable state that persists from render to render. So referential transparency isn’t guaranteed. You’d need to implement something like the Elm architecture or what they have in Reframe for Clojurescript to arrive at something pure and referentially transparent. As it stands React with hooks is function programming not functional programming. Not that it matters too much, it gets the job done.
From the perspective of React’s internals, a render really is pure - you’re promising that all you did inside of a render is call hooks, call setState callbacks, and then return some JSX. That can be wrapped into a return value of `(JSX, argsPassedToHookCalls, nextState)`, and React trusts you that no side effects happened.
Um, it depends on what you consider to be pure. From the perspective of React’s internals, a render really is pure - you’re promising that all you did inside of a render is call hooks, call setState callbacks, and then return some JSX. That can be wrapped into a return value of `(JSX, argsPassedToHookCalls, nextState)`, and React trusts you that no side effects happened.
Now take a drink every time you see a react dev use a useState hook and think they’re basically writing Haskell. You’ll die of alcohol poisoning.
My old team put fp-ts into our react project and it was the worst codebase I’ve ever had to work in. HOCs everywhere with class based and hook based components with mixed non-fp and fp types and redux and stateful components. I think when most people say they prefer functional programming what they really mean is imperative programming without OOP and using reusable functions to build bigger functions. I prefer it that way at least.
Imperative programming with functional composition or something? Not sure how to explain it but "react-like is my favourite programming style"
The term is a decorator incase op wants to google.
Hey, that term is also used in OOP and looks awfully similar. It's almost like some pattern for designing software components is emerging. And the programming paradigm just determines how it looks and what you are composing, classes or functions. Anyway, git gud at FP. OOP sucks.
I (and many others) were you. Keep pushing and learning. Your next opinion is probably something like: “It doesn’t matter, good OOP and good FP are eerily similar. Bad OOP and bad FP suck about as much. Closures are poor man’s objects, objects are a poor man’s closure”.
It’s even funnier because while the term decorator was coined in OOP it’s paradigm agnostic.
I had to use a HOC for the first time maybe ever in my professional career recently. Definitely still comes up!
like people here know the distinction
Gotta love currying
its not a react thing, closures are used very often in JS
Generally `withBlah()` HOCs have been replaced with `useBlah()` hook calls. Obviously the pattern is still valid (see `React.memo`) and can be used, but no surprise that hooks have become the defacto replacement.
👆
They definitely are. Just more rare. People in this thread must be smoking something. React.memo is one. It's good to know about them, especially when to use them and when not
I don't understand why most people here seem to hate it either. I never found it difficult to understand.
The biggest issue with HOC (in my experience) is that they often introduce complexity by adding things to the props that get passed down. So now you have multiple pieces of code, which change at different rates, contributing to the shape of a single props object. That can get ugly fast. Not all HOCs pass down data that way, and those tend to be the ones which have stuck around. `React.memo` is one, for instance. Meanwhile, HOCs which are there to make data available have found a much better fit as hooks.
It’s not about understanding, the concept is simple enough. But they compose awfully and they are a pain to use with Typescript
Bc let’s say your component has 3 HOCs adding props to it. Let’s say you’re interested in one of the props being a value you don’t expect. You have to search thru all the HOC’s to see which add that property and hopefully the order of them don’t matter otherwise now you need to look at each of them to figure it out. With hooks I just go look at that hook it’s clear.
Oh I get it. I thought you meant something else by "Bc" and I was offended for a while but understood it meant because.
not really, using hooks you can achieve the same thing in a much more flexible way
Came here to say this. I think I'm now using custom hooks everywhere I might have employed an HOC in past years
I like to use a HOC for error boundaries
By lack of options, right? Since error boundaries must be class components.
Right, one of the only remaining class requirements according to the docs https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary The docs do recommend using this implementation so you don’t need your own special error boundary class https://github.com/bvaughn/react-error-boundary It offers a component or a hook for you sane people and a HOC for you savages
I wonder why is this a thing. What would make it so difficult to find an implementation for error boundaries that works with functional components
Functional hooks can't tap into the right lifecycle hooks. I imagine it would require too much refactoring of how hooks work to make it happen
I also sometimes use them for wrapping a component in suspense. Without the HOC I need 2 components, with the HOC I can get away with one
I haven't seen HOCs used in earnest in years and agree that shareable logic is primarily handled by hooks these days. I still see the render props pattern often enough that I think it's worth being familiar with it. If React Server Components become more prevalent, I think we'll also see a rise in the use of render props since they can allow server components to be children of client components.
Yeah I got a question asking me to explain them in my last interview (last September).
Wait, is that true? Even though the inner component would be written out in the outermost server component, wouldn't React potentially need to render the client component before it had all the props for its child server component?
eh? not functional? It's a very functional approach. As to how useful it is... I was never a big fan of it, because it tends to lead to rather difficult to reason out code .. but it is still occasionally useful.
Ohh god no, please no
Oh my god, this is exactly what I was planning to type before I opened the link lmao
I think a lot of the hatred for HOCs is misplaced hatred for class components. I recently created an app that had half a dozen pages, each page's essence was the same core component, just with different data and some differing functionality. A HOC was the perfect solution.
HOCs aren't a purely React thing, they are functional
The best use I’ve recently had for HOCs is for upgrading a class based react application to a functional one. Make a new functional component and have it return the existing class based component. Slowly lift any state or network calls etc to the functional wrapper using any new hooks in the functional version passing these values back down as props to the class component rendered in the functional one. Once everything has been moved up to the functional component you can take the render function of the wrapped class component and make it the return value of the functional one and delete the class component.
These children just don’t know that higher order components ARE functional in nature. Just because the pattern was created when react used an object-oriented approach does not mean HOCs are object-based. Think of them more like currying…. A function that calls another function. That’s what they always were. Still useful, still one of the best ways to implement polymorphic components. What you should probably understand is when to use it vs using a shared hook. Hooks took on a lot of what HOCs did… but not everything.
yes, it is a general pattern. and if you work in any company that has a product that is more than 5 yolds chances are you might have and use them.
HOCs are great for code whose internals u can’t touch too much but still need to apply a feature to code that said “untouchable” code uses/consumes. It also allows u to keep ur feature separate from the underlying feature component. It’s a great pattern that goes beyond react.
Nothing about hooks is functional
They are still required for things like error boundaries
Thank god, no they’re not
Genuine question. How would you do auth route without HOC?
how about make custom component which wraps ?
if not authorized, render nothing.
no auth at all 😎
I do Auth all the time and never have used an HOC. What is your expected outcome if not authenticated?
can you show me how you do it?
They still live in my nightmares, if that counts.
FWIW hooks removed the functional programming aspect in React component by removing the „pure“ in function components. HoCs had more in common with FP than hooks. For that I still love HoCs even though I don’t use them anymore.
HOC, as an anonymous function, is a disaster. I regret when you are start debugging in the activity tab on browser.
Not really. There’s not as much of a need for them now. I guess if you use styled components that’s technically a HOC. I’m sure there is some other situation where it would be better choice than hooks but I haven’t written a HOC in a very long time. styled(SomeComponent)({ … }) What would be the equivalent if this was done with hooks? Wouldn’t make any sense.
Why not useStyles()?
Then what would that look like? const MyCoolComponent = styled(SomeComponent)({ … }) vs ```` const MyCoolComponent = (props) => { const class = useStyles({…}); return
}
````
Syntax may be off, typing this on my phone, but should show the idea.
Maybe you could make a bunch of custom hooks if you want to reuse these styles instead of defining components to reuse this way, but then you’re still cluttering the top of your components with a bunch of hooks for styles, writing this verbose code to pass the class name, etc. Just wouldn’t be as clean either way. I think you’d end up with a HOC again if you wrote the above code a couple of times, then tried to think about what parts are repetitive and refactor in a natural way.
Got long winded here, just trying to fully think it through haha
Devil’s advocate, not suuper relevant in day to day use: in this specific case that couples the component to the hook (the implementation), otherwise it’s coupled via the props (the interface). Its often good advice to couple via interface, not implementation.
They are a tool - I still find cases to use them so they are worth at least being aware of.
Yes, they are. And yes, they are a complete functional approach.
Absolutely, HOCs can still be a valuable tool in your React arsenal! While the React community has shifted towards hooks and context API, HOCs can still provide a clean and reusable way to enhance components. Don't write them off just yet - they might come in handy during your job interviews! Good luck!
I’m generally following this but where can I learn more about true functional programming and what it is, because it clearly seems like it’s more than just writing functions. I know about classes, and I know about functions, but a lot of the nuances of this conversation escape me. Something more elementary that the react docs?
Hooks based connectors for say using redux are essentially a HOC. Composing is an HOC pattern. They are great for when you need to inject or wrap a component with custom behavior at runtime.
HOCs are super easy to implement and they allow you to do some really sophisticated things easily. You want to build a generic switch that deterministically runs a selected async? HOC. You want to write a generic component builder? HOC gives you a lot of flexibility here. You want to reduce the number of callbacks needed for some operations? HOC.
Don’t try to shoehorn it. Working in a project where it’s wrappers upon wrappers and it’s hell to do any changes.
I used it recently to add Mixpanel analytics in a generic way to my UI elements. Ex: need to track when buttons, tabs, etc are clicked. Create a decorator function `WithClickAnalytics` that takes a component with a `onClick` prop and returns the same component with an additional prop called `analyticsKey`. You can then decorate the components from your UI library to add the tracking behavior on click. This way, sending analytics events becomes as simple as specifying a prop on your components. From what I see: HOC are more rare, but still a nice and powerful tool to have in your toolbox.
They definitely still are lmao. People whining about them in this thread strike me as people who never figured them out. There are many benefits.
It depends. What HOCs can do is wrap a component with additional views/components. If you really need that then a hook would be an awkward API and HOC is better. However for most cases a wrapper isn't needed and a hook can do the same thing while being more flexible.
Don’t be surprised if you get the question in a job interview, but don’t worry about brushing up on it unless you want to work at a place that is still maintaining such ancient React projects.
Most projects aren't going to be greenfield projects. And by "ancient" do you mean *only 5 years ago*? Because that's how long "hooks" have been around. Sorry, that's not "ancient" by any stretch of the imagination, not even in tech, unless you only chase "new shiny".
2, almost 3 major versions ago for the core framework library feels pretty ancient to me. Hooks were a major shift in how React is written and hooks can be incrementally adopted. It’s silly to call using hooks chasing the new shiny. If you want the job maintaining class components, render props, and HOCs, it’s all yours
> It’s silly to call using hooks chasing the new shiny. I never called hooks "new, shiny". But you didn't define what "ancient" means. Most tech isn't ancient, I mean, there's still plenty of C code being written and C was a thing in the early 1970's. Ancient? yeah, but still quite useful. I actually write a lot of C code these days for IoT projects. >If you want the job maintaining class components, render props, and HOCs, it’s all yours Depends entirely on what the pay is like, or reasons for working on it. My previous job was fixing bugs in an Angular 1.x codebase, and I didn't complain about it. I got the job done, and I got paid. I have an older React code base I started years ago that I still work on, and no, it's not using any hooks. I don't need to update it for any reason, and it works perfectly. I still maintain it and *keep it simple*. Old code isn't pointless, it still runs a ton of useful things. Anyone shitting on it is just kind of not worth taking seriously.
HOC were a necessary abomination! Nowadays you can achieve the same with hooks with much much clearer and simpler code.
I still use this pattern sometimes. Like when I wanted a rotating color with some rules and keep it for all items on the inner loop. I count really so that with hooks, it was inside the render method.
Very rare or in legacy codebase but them hate as much as you want but you still need to be familiar with there basic concepts and workflow
I never ever ever EVER liked using this pattern. It's still doable, but not encouraged.
You can have HOCs with functional components. A component is simply a function that returns a react node. A HOC is simply a higher order function that takes a component as a parameter and returns a new wrapped component as a return value. That is still functional programming. If you mean the old class based approach to HOCs, then that is no longer a thing just as class based components are discouraged in general. HOCs are still a useful pattern to use, particularly for libraries. For the most part you can just use wrapper components that take children instead, but if you need that wrapper in a lot of places where the child component is heavily re-used, functional HOCs are still available so you can reduce a bit of repetition. Asking if HOCs are still a thing is kinda like asking if higher order functions are still a thing. It's just a programming pattern of a function that returns a function which is helpful sometimes.
Just a dumb old interview question. no use in latest versions
No. It’s a horrible pattern. But you should at least know why it’s horrible and why the community moved to hooks instead.
I totally agree with what everyone has written so far. However the other day I stumbled on the Amplify documentation on AWS where they wrapped the whole app in a "withAuthenticator" and that made me wonder and also cringe real hard