r/reactjs • u/Stevious7 • Jun 08 '26
Discussion I'm a bit confused about custom hooks
I'm trying to wrap my mind around custom hooks. As far as I can see, they seemed to be regular functions with React's hooks embedded within. I'm trying to internalize the mental model of how it's all supposed to work to not fall into an anti-pattern. I'm using AI to learn, so I asked about examples of custom hooks and the response made me raise an eyebrow.
The way AI was using custom hooks is to return state and state setters from the custom hook. I guess that works, but that can't be all. Right...? Also, I'm not sure if React allows this, but couldn't we have used OOP to encapsulate the data and the associated methods instead of the custom hook?
What I was making was a data store for the whole application that holds the application's current state (like which tab the user is on right now, which peer is the user currently connected to, etc...).
Could anybody point me to a good example on GitHub that I can reference as good use of custom hooks? When do you guys get the "eureka" that something should've been or should be a custom hook?
Thanks in advance
45
u/Ivana_Twinkle Jun 08 '26
Basically you use it to abstract code from your components that are reusable and doesn’t fit in regular functions. In hooks you have access to react lifecycle elements that you can’t use outside react elements. State can be an option. Other react hooks like useEffect is another.
Think of it like functions but you can use reacts api in them.
5
u/octocode Jun 08 '26
the docs are probably a better place to start https://react.dev/learn/reusing-logic-with-custom-hooks
AI is pretty slop at explaining react concepts since a large chunk of it was trained off of random reddit comments
2
u/Renan_Cleyson Jun 08 '26
If I understood correctly your concern is because the custom hook examples weren't encapsulating anything. Custom hooks actually can and you most of the time will encapsulate some logic on it but custom hooks are more about composability and less about encapsulation. So yeah the AI examples were probably fine but the point of custom hooks like I said is mostly composability, you do care about encapsulation but it's rarely useful to encapsulate the same way we do with OOP.
I think you should clear your mind about React and restart without trying to thinking in other terms like OOP. Just look for the React way of building UIs
16
u/Antti5 Jun 08 '26
I think your mental model should be: Custom hooks collect logically related states and other hooks into one place.
Imagine that you are building your app and your components keep growing in size. You split big components into smaller ones, and do it so that you try to create reusability to the extent possible. Custom hooks are about the exact same thing, however unlike components not including any rendering but only logic.
And even if your custom hook isn't really reusable, it can make your code more readable if you move the logic away from the component to a custom hook.
It is indeed typical that your hook returns states and state setters. However you should not find yourself returning everything from inside the hook, but only the states and setters that are relevant for the users. What remains inside the hook is what makes it valuable.
2
u/gmaaz Jun 08 '26
If you use hooks for data store know that they execute on every call/rerender, they don't share the state between them.
4
u/friedmud Jun 08 '26
I feel like most of these answers miss the main mental model of hooks:
You can think of them as taking the code in the hook and placing it IN the component they are called from. Basically, think of the hook code being copy/pasted into your component where the hook is called.
This allows you to encapsulate routine logic in your functions into reusable pieces.
5
u/lightfarming Jun 08 '26
you really need to read up on how react state and rendering works or you will be lost. this is quite a bit you are asking people to teach in a simple reddit comment.
2
u/Practical-Skill5464 Jun 08 '26 edited Jun 08 '26
Yes that is right. The feature it's using is called closures.
TLDR if you define things in a function and pass them in a return they'll be kept around along with anything it relys on inside the funciton until you stop using them and the trash collector cleans them up.
Yes React at one point did use classes. That was the original component design before Functional Components. But that sort of inheritance/mix-in model sucks because it makes it very hard to see what came from where and if you have definition collisions - particularly when you are several layers deep and didn't have any type system. It's the same reason Vue3 ditched the class based mix-in model in favour of React style hooks with extra steps.
2
u/Dreadsin Jun 08 '26 edited Jun 08 '26
You know how sometimes you have a function that gets way too big and gets confusing, so you abstract out parts of it into separate functions? You might also even do this with components. The exact same applies with hooks
In a very simple case, imagine that you wanted to make a “toggle” — it provides a
isOpenandtogglefunction in a tuple of two items, similar to auseState. We may implement it like soNow instead of re-writing that logic every time, you can just use this hook as if it’s a
useState,useReducer, etc etcThis is a simplified case, but you may put together several different hooks together into one big one. The idea is really just to put together any number of hooks and then (almost always) return a hook or
void1
u/Cahnis Jun 08 '26
Its like a function for your react conponent internal code. Helps makes it testable and organized
1
u/prehensilemullet Jun 08 '26
Some popular examples of custom hooks are TanStack Query’s
useQueryfor data fetching, React DnD’suseDraganduseDrop, andreact-use-measurefor responding to the sizes of DOM elements.I’d recommend looking at what behavior those provide to a component conceptually, and then look under the hood to see how their code is built on top of React’s core hooks.
1
u/azangru Jun 08 '26
We could. But react doesn't :-)
Something needs to tell react to re-render when a certain value changes, so that the UI is consistent with this value. That's what the hooks do: they hook into react's render cycle, and either cause a component to re-run the rendering logic, or fire after a component re-renders.
How would you achieve this with OOP, given the constraints of the react api?
1
u/n0tKamui Jun 08 '26
hooks are just functions that are not components and call other hooks. that's literally just it.
you create them for the same reasons you create any other function: abstraction and encapsulation of logic
1
u/Joee94 Jun 08 '26
Everyone overcomplicates this. Just think of it as a function, except that function needs to call a hook. If you need to abstract some common code into a function but it requires a hook, make it a custom hook
1
u/MehYam Jun 08 '26
The comments here are missing something: a hook is just like a component, except it uses regular function syntax, not props, and it's not required to return a component.
Put another way, a hook is a function that's able to call hooks. A component is that plus it takes props and returns a component.
1
u/Seanmclem Jun 08 '26
That’s what they are. Custom functions, with hooks inside. Starting with the name use. Normally hooks need to be used at a top level. You can’t just nest them inside of a function in your component and expect them to work. So, custom functions that consume hooks become hooks themselves and fully entered to the hook’s life cycle.
1
u/AverageHot2647 Jun 10 '26
You’re correct, custom hooks are just regular functions which call other react hooks. I think it maybe helpful to understand a bit about how hooks work in React.
Basically, when you return a
<MyComponent />, this is compiled toReact.createElement(MyComponent, null);. This gives React control over how to call your component function, but it doesn’t know anything about your component other than which function it needs to call to render it.So, what’s this got to do with hooks? Well, when React calls your component function, that function may call any number of hook functions. But React knows nothing about the structure of your component, so all React knows is a timeline of Which hooks were called in which order e.g.
Note that React has no visibility of how these hooks got called. That means that it doesn’t matter if your component calls the hook directly, or if it calls another function which then calls the hook, or whatever.
So hopefully you can see that there really isn’t any such thing as a “custom hook”. The only thing that matters to React is which React hooks get called and in what order.
If you understand it like this, it also makes it clear where some of the rules of React come from. For instance, you’ll see in the React docs that you can’t call hooks unconditionally. Let’s look at why:
Imagine that on the first render,
conditionistrue, and on the next render it isfalse. Would you expectstateBto equal "a" or 42?The answer is that
stateBwill equal "a". Why?Well, on the first render, React observes that
useStateis called once with an initial value of "a". On the second render, it sees thatuseStateis called once, and assumes this is the sameuseStatecall as the first render, so it returns the current state, "a".Interestingly, that also means you can technically call hooks conditionally, so long as the condition never changes for the lifetime of the component instance.
I’d encourage you to mess around with this in a playground to see what breaks, when, and how. This will give you a better feel for how this all works. You can also read the React source code.
0
u/NotLyon Jun 08 '26
Since you're learning, this should throw you through a fun loop. Hooks can be components and components can be hooks. Don't do this, but it works (in ways you might not yet understand)
0
u/TechnologyRound2582 Jun 08 '26
Custom hook is used when one needs to use a common function utility that uses react state or effect.
The state vars and effects defined in custom hook are attached to the individual comps for each comp. Each comp gets its own state and effect attached to its own fiber node. The custom hook itself does not store any state.