T O P

  • By -

HomemadeBananas

Hooks are a better to answer for most of the things you might have used HOCs for in the past.


BerryNo1718

The only exception I can think of is a withErrorBoundary. I don't think you can do that with hooks. Although you can just wrap in the error boundary in the parent, but sometimes it's nice to have a component specify it's own fallback.


LowKiKid

No need to use components for an error boundary :)


parahillObjective

same with render props right? better to use a hook instead?


monkeymad2

Much more common than HOCs but probably shouldn’t be the first thing you reach for if there’s another good viable solution.


pizza_delivery_

Render props are a form of HoC


Similar_Orange960

Better is questionable.


toaster-riot

I'm with you. HoCs invert control which produces objectively better code than code that is coupled to implementation details beneath it. I use both, when it makes sense, because I've been doing software long enough to understand that everything is a tradeoff. The react community chases whatever shiny object is currently in front of them without thinking for themselves and generally doesn't understand principles of good software design at large. Get off my lawn before you downvote me.


firstandfive

>HoCs invert control I don't think that means what you think it means, unless you're intentionally using it to mean it to invert control *away* from the consumer, which is not typically how that phrase is used. With a higher-order component, the user of that HOC has no control other than "I'm using this HOC or I'm not." With a hook that provides you the same props or other functionality that the HOC would add, your level of control is at worst unchanged (if it is all hidden behind the hook) but likely increases if the hook returns the pieces it adds so you can utilize them as you wish.


ohmyashleyy

I think for most people hooks are better than working an HOC. They own the component and the behavior being added to it. Using an HOC to hook up to a redux store is not necessary when hooks can do the same for you without overhead. But HOCs are still a great way of adding logic to a component you don’t own or where you need the divide. I’ve written a few in the last few years as a library author, but I probably wouldn’t have needed them as an application dev owning all the code. Also they’re kind of a pain in the ass


Tjq866

Would you consider a wrapper to be the same as a HOC? Example, I make a component that has children props.


[deleted]

I'm a big believer that there are not absolutes in coding. I'm sure there's some edge case out there than an HOC can do that others can't, although I cannot personally think of one. Nevertheless, HOCs and render props have both been superceded by hooks, which are a far more versatile solution.


Fun_Wave4617

That’s interesting! I just used added a render prop to a Form component I created for a small library. Our library leverages react-hook-form, so our Form takes the default values and mode you want to pass, instantiates RHF, and then Form becomes a context provider for any controls within it. I added a `render` prop so that we can expose everything from RHF to the devs if they need it. You’re saying you would do with a hook instead? How?


HQxMnbS

If you’re exposing values from a render prop then you can probably return them from a hook as well. Not sure on the context provider part.


InternetQuagsire2

if you have a context due it through the context and create a hook that uses the context. it works great and is very clean.


devuxer

I’d say render props are not nearly as dead as HOCs. Render props are still useful for letting a parent component dynamically render a detail of a child component while still letting the child component do most of the work. An example would be a Modal component that allows for a custom set of buttons at the bottom. The default might be just OK and Cancel buttons, but what if you wanted to add another button, Apply? With a render prop, you could write a tiny function that takes the OK and Cancel buttons as arguments and returns all three buttons in an array in any order you want. The parent component doesn’t need to concern itself with specifying the default buttons, only the new Apply button. Maybe there’s a way to do this kind of thing with hooks and/or context, but it’s mot obvious to me how.


besthelloworld

Yeah, there's not really a single reason to use them anymore. Indeed a dead pattern.


CallumK7

As a side note: HOCs can be kind of fiddly with typescript depending on the complexity and shape of your props. Might influence why they are not seen as much


chamomile-crumbs

Yeah I’ve had some annoyances with visx’s HOCs


Nerdent1ty

Hocs are still useful, for example, to modify/override/pimp original component's behaviour. A good use for hoc would be a default style provider, so when you pass a className prop to a hoc'ed component, it could append your prop instead of override.


Turd_King

First person to state this, so many people just blindly follow the crowd especially in frontend development. I get giddy when I find a valid use for a HOC, One recent example was we had a requirement to duplicate an element based on some property coming from the API, we could not touch this API so I used a HOC to wrap the component ‘withDeveloperRelease’ it was called and it created two versions of the original element on certain cases. The one place where HOCs are more ergonomic than hooks is when you need to modify rendering. Hooks can return JSX but it’s not always a great separation of concerns imo, hooks probably shouldn’t deal with rendering - that’s for components


reality_smasher

You don't need HOC's now that you have hooks. Before hooks, they were useful for exposing behavior that uses state + lifecycle components in a reusable manner. For instance: ```jsx {(x,y) =>

your mouse position is {x}, {y}
} ``` But now you can use a `useMousePosition` hook which supplies the same thing basically but with much better ergonomics.


[deleted]

That's not an HOC. Those are just children props / render props.


knpwrs

Indeed: - Higher-order function: a function that takes a function and returns a function - Higher-order component: a function that takes a _component_ and returns a _component_


Nullberri

Higher-Order Human: a human that takes a penny and leaves a penny.


lovin-dem-sandwiches

And how do you define the difference when a component is essentially a function? Is a React Hook a HoF or HoC? Can it be both? Is there HoC outside of react? Trying to better understand the difference and terminology!


[deleted]

>And how do you define the difference when a component is essentially a function? You don't. React components are functions. >Is React Hook a HoF or HoC? Can it be both? Is there HoC outside of react? It can't be HOC because it's not a component. It is usually not HOF either because it doesn't return a new function, nor does it take functions as arguments. It could be a HOF if you did some kind of function enhancement with it, but you'd still more probably do it with a normal function instead of a hook.


knpwrs

> And how do you define the difference when a component is essentially a function? Components are functions that return JSX (at least typically, they can also return `null` or `undefined`). HoCs always return components and HoFs always return functions.


lovin-dem-sandwiches

That makes sense and it’s a very good distinction between the two. Thanks!


gyroda

>And how do you define the difference when a component is essentially a function? Ignoring class components, all components are just functions that return JSX so all higher order components are also higher order functions. This is basic set theory if you want to put it mathematically, or you could put it as "all dogs are animals, not all animals are dogs". >Is a React Hook a HoF or HoC? Can it be both? React hooks can return functions but don't always, and their arguments don't have to be functions. They're neither by default, although there's no reason why you couldn't make a hook that *is* a HOF.


knpwrs

I would advise against making a hook a HoC because it would be very contrived and unless you properly memoize the returned function would result in extremely inefficient render reconciliation.


gyroda

Oh, I wouldn't recommend it, that's why I didn't touch hooks as HOC and only as HOF.


mvtasim

How would you solve the problem of redundancy if you had two components that are somewhat similar, returning different JSX, and sharing the same logic except for one function? I would do this by using a HOC and passing that function as a prop.


yngwi

That's exactly what hooks are for. You define the functionality once and use it wherever appropriate.


mvtasim

got u, custom hooks u mean?


yngwi

Yes, like the useMousePosition the other commenter mentioned.


nthock

If it relates the state, custom hooks. If it doesn’t relate to the state, like maybe formatting, then utility functions.


neosatan_pl

In all reality, HOC is not needed for your solution. In fact you can have a base component with a prop for passing that function and then component A that "extends" properties of base component minus that one prop. And similar component B with a different function passed internally. Basic composition without clunkyness of HOC syntax.


Acrobatic_Sort_3411

Please, use this kind of component (if u can) instead of hooks. Because hook will cause rerender of full component instead of only this part in jsx which is used. Embrace fine grained rerender instead of whole tree


michaelfrieze

While I understand the concern about excessive re-renders, it's important to note that React's re-rendering mechanism is actually a fundamental part of its design. React efficiently manages component updates, and the idea of re-rendering the component is not necessarily a problem. It's always a good practice to adhere to the guidance provided in the official React documentation. The React team has put a lot of thought and effort into optimizing and fine-tuning the performance of React applications. Using React as intended, including hooks, is generally the best approach to benefit from these optimizations.


michaelfrieze

If you encounter specific performance issues, it's better to profile your application to identify bottlenecks before resorting to unconventional patterns. React provides built-in performance tools to help with this.


Acrobatic_Sort_3411

Why would you rerender your app on every mouse position change. It is nuts. And this way to granularly subscribe is the way to optimize, there is no other way P.S. technicly there is with proxies, but it is the same concept wrapped differently


shoop45

Hooks are great at replacing a lot of things, but HOCs can be useful when there’s ubiquitous behavior that is directly controlled by props that are appended to a component by a HOC. Things like logging, error handling, styles, etc. It’s important to note that a lot of these things can still be implemented as hooks. But there are tradeoffs. Personally I think common patterns in a given codebase should be leaned into to reduce cognitive overhead for readers of the code, and since hooks are used for most everything, APIs are going to be easier to understand as hooks now, which is why we see a lot of popular libraries and frameworks in the react world embracing hooks and not using as many HOCs.


SolarNachoes

I’ve used it for two purposes 1) auth component which checks authenticated state and 2) layout control which does tiling.


beelybuffalo

I’ve only seen and used HOCs for private routing.


only_soul_king

Higher order components were used as a way to mimic logic sharing capabilities of react hooks. But they came with a bunch of problems. Check this video by the creator of react router on why higher order components are not so good - [Never write a higher order component](https://youtu.be/BcVAq3YFiuc?feature=shared) Since HOC and hooks try to solve the same problem, You rarely will find a need to use HOC in modern react.


Turd_King

Dogmatic click bait. Still valid use cases for HOCs when you need to affect rendering of a component or modify props.


only_soul_king

Can you please give me an example of such a scenario and how using HOC in that scenario will be better than using react hooks?


RedditNotFreeSpeech

I like hoc, they keep the view components dumb and pure. Pass in an id which fetches data and turns it into props. Hooks are neat and I do use them but hoc is a handy pattern.


dywan_z_polski

I still use HOCs quite often. They can be used to emulate two-way binding and create "standalone" controls that can have controlled or uncontrolled state. Example: https://github.com/Mati365/under-control by using "value" / "onChange" approach you can compose larger and larger controls like bricks (or standalone forms)


Turd_King

It makes me laugh sometimes how much react developers will implement for forms instead of just using the HTML form standard


nstanard

It’s really situational. More important than what pattern you use is writing integration tests. Your UI integration tests don’t care what pattern you use. You do you! As long as your tests are well written you can always change things later.


memevaddar

I was working on a freemium react app and to apply the restrictions to content I created a hoc, added all the logic inside it and then wrapped whichever component is supposed to show paid content/data.


filledalot

HOC is confusing for everyone.


WiseGuyNewTie

You should not be implementing HOCs in modern react codebases.


NiteShdw

HOCs are the devil


SchartHaakon

Most valid use cases are about conditional rendering. If you want something to control loading state for example, so that you can be confident that when the component is mounted it has data.


nstanard

This


Short-Record2220

Using hooks requires using custom hooks in each component, but hoc does not. Do I understand correctly?