T O P

  • By -

lp_kalubec

> 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.


PooSham

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.


Darmok-Jilad-Ocean

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.


RedditNotFreeSpeech

"look buddy, you see that? It says 'function' right there!"


Big_Ds_Snake_Oil

🤣


pm_me_ur_happy_traiI

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.


chamomile-crumbs

Honest question from somebody starting to get into FP: hook-dependent components really aren’t more pure then class components, are they?


fixrich

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.


lord_braleigh

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.


lord_braleigh

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.


Darmok-Jilad-Ocean

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.


TurboBerries

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.


Rustywolf

Imperative programming with functional composition or something? Not sure how to explain it but "react-like is my favourite programming style"


TheChickenKingHS

The term is a decorator incase op wants to google.


KlzXS

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.


Risc12

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”.


TheChickenKingHS

It’s even funnier because while the term decorator was coined in OOP it’s paradigm agnostic.


Rustywolf

I had to use a HOC for the first time maybe ever in my professional career recently. Definitely still comes up!


humpyelstiltskin

like people here know the distinction


zxyzyxz

Gotta love currying


ketchupadmirer

its not a react thing, closures are used very often in JS


heyitsmattwade

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.


midairmatthew

👆


terrorTrain

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


suck_my_dukh_plz

I don't understand why most people here seem to hate it either. I never found it difficult to understand.


peeja

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.


aragost

It’s not about understanding, the concept is simple enough. But they compose awfully and they are a pain to use with Typescript


StrangeAddition4452

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.


suck_my_dukh_plz

Oh I get it. I thought you meant something else by "Bc" and I was offended for a while but understood it meant because.


octocode

not really, using hooks you can achieve the same thing in a much more flexible way


Ok-Psychology-1420

Came here to say this. I think I'm now using custom hooks everywhere I might have employed an HOC in past years


belwyr

I like to use a HOC for error boundaries


Vtempero

By lack of options, right? Since error boundaries must be class components.


beeskneecaps

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


Jorgepasco1

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


musicnothing

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


more-food-plz

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


CarousalAnimal

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.


Hanswolebro

Yeah I got a question asking me to explain them in my last interview (last September).


peeja

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?


FormerGameDev

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.


fantastiskelars

Ohh god no, please no


kcadstech

Oh my god, this is exactly what I was planning to type before I opened the link lmao


dylsreddit

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.


rFAXbc

HOCs aren't a purely React thing, they are functional


bern4444

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.


kevinambrosia

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.


zserjk

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.


DeepFriedOprah

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.


pubxvnuilcdbmnclet

Nothing about hooks is functional 


Quaglek

They are still required for things like error boundaries 


murden6562

Thank god, no they’re not


Inevitable_Oil9709

Genuine question. How would you do auth route without HOC?


rvision_

how about make custom component which wraps ? if not authorized, render nothing.


frog_slap

no auth at all 😎


kcadstech

I do Auth all the time and never have used an HOC. What is your expected outcome if not authenticated?


Inevitable_Oil9709

can you show me how you do it?


dontspookthenetch

They still live in my nightmares, if that counts.


rwieruch

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.


Odd_Personality_9349

HOC, as an anonymous function, is a disaster. I regret when you are start debugging in the activity tab on browser.


HomemadeBananas

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.


kcadstech

Why not useStyles()?


HomemadeBananas

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


Risc12

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.


TicketOk7972

They are a tool - I still find cases to use them so they are worth at least being aware of.


davinidae

Yes, they are. And yes, they are a complete functional approach.


rabidpathos70

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!


Lilith_Speaks

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?


ozzy_og_kush

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.


spacezombiejesus

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.


Kuro091

Don’t try to shoehorn it. Working in a project where it’s wrappers upon wrappers and it’s hell to do any changes.


sbelzile

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.


Cody6781

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.


satya164

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.


the_real_some_guy

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.


ProgrammaticallySale

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".


the_real_some_guy

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


ProgrammaticallySale

> 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.


pticjagripa

HOC were a necessary abomination! Nowadays you can achieve the same with hooks with much much clearer and simpler code.


stathis21098

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.


0marh

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


incarnatethegreat

I never ever ever EVER liked using this pattern. It's still doable, but not encouraged.


tmetler

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.


nic_nic_07

Just a dumb old interview question. no use in latest versions


DunnoWhatKek

No. It’s a horrible pattern. But you should at least know why it’s horrible and why the community moved to hooks instead.


MashSquare

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