React hooks have revolutionized the way we manage state and side effects in React functional components. With hooks, we can encapsulate reusable logic and share it across components, leading to cleaner and more modular code.
In this article, we'll explore the top 7 React hooks that every React developer should know about. Whether you're just getting started with React or looking to level up your skills, understanding these hooks will empower you to build more efficient and maintainable React applications. Let's dive in!
useState()
useState
is a React Hook that lets you add a state variable to your component which returns an array with two values.
- Current State
- Set Function
You can pass on initial value as well like in the example:- 28 and 'Taylor'
import { useState } from 'react';
function myComponent() {
const [age, setAge] = useState(28);
const [name, setName] = useState('Taylor');
}
useMemo()
useMemo
is a React Hook that lets you cache the result of a calculation between re-renders which prevents the unnecessary renders in your React Application.
import { useMemo } from 'react';
function TodoList({ todos, tab }) {
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
}
useId()
useId
is a React Hook for generating unique IDs that can be passed to accessibility attributes,
Accessibility attributes let you specify that two tags are related to each other where you can use useId()
generated id instead of hardcoding them.
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
return (
<>
<input type="password" aria-describedby={passwordHintId />
<p id={passwordHintId}>
</>
)
useCallback()
useCallback
is a React Hook that lets you cache a function definition between re-renders.
useCallback cache a function and useMemo
cache a value/result of a calculation
import { useCallback } fom 'react';
export default function ProductPage({ productId, referrer, theme }) {
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy' {
referrer,
orderDetails,
});
}, [productId, referrer]);
useEffect()
useEffect
is a React Hook that lets you perform side-effects in the component. Side effects basically is an action which connects the component to the outside world.
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
}
useRef()
useRef
is a React Hook that lets you reference a value that's not needed for rendering.
Basically its like useState
but the only difference is useRef
doesn't cause a re-render when the value changes.
import { useRef } from 'react';
function MyComponent() {
const intervalRef = useRef(0);
const inputRef = useRef(null);
}
useContext()
useContext
is a React Hook that lets you read and subscribe to context from your component just like a data store (Redux)
useContext
hook mets you to read the data stored in a context which is a data store
This example is just to demonstrate useContext hook not creating a Context
import { useContext } from 'react';
function MyComponent() {
const theme = useContext(ThemeContext);
}
React hooks are a game-changer for React developers, offering a straightforward way to manage state and side effects in functional components. By mastering the top 7 hooks discussed here, you'll be better equipped to build efficient and maintainable React applications. Keep exploring and leveraging the power of hooks to enhance your React development journey.
Happy coding!π
π‘ Letβs Connect!
π© Email me at: getintouchwithvishnu@gmail.com
β Support my work: Buy me a Coffee
Top comments (33)
useMemo and useCallback will be useless with react 19! :)
Really why? I mean, I always found them useless unless your dealing with a seriously flawed react application. I really build everything with just useState and useEffect, when those statements are a paragraph chunk of related gunk, I plop them in a custom hook with support functions near... once lifted appropriately. I tried reducers for some more complex data but honestly it hurts more than it helps 99% of the time, unless it's a global reducer in redux of course.
Anytime I do anything else with hooks in react, tends to cause issues, if nothing more than in coder comprehension and maintainability.
Only two hooks one should use imho, the rest aren't as good as a custom hook usually.
@gunslingor what you are describing is not react, but practically any other framework.
Reacts flawed reactivity model requires some form of memoization to prevent re-rendering, because it uses the component functions as units for state management. Compare that with Vue, or Solid, or Angular, or Svelte, where the main reactivity unit is a signal enabling modular rendering only affecting the part of the dom that was changed due to state changes.
Not sure I agree. What you are describing is a react app where state is not correctly under control, where things are rerendering when they should not, when no props have changed i suspect. When state lives in the level and component it should live in, rerendering happens when it should.
Components rerender when THEIR state changes (internal) so it should know better than anyone when it needs to rerender for this.
Components also rerender when their parent renders, and parents rerender when their state changes, or parent rerenders because their state changes... so their should be a state waterfall similar to DB relationality... when your DB is solid, your not using anything fancy.
Also Context changes, again though all stuff the dev has under control.
React is more opinionated than the frameworks you mention all of which ive used or tried over the years. React is component based to encourage controlled state, but its also extremely flexible so people often fail here and most react components I see in corporations are monstrosities... useMemo is a dead give away usually, because it's in a frankenstein function so no way it's being used as the vendor intended:
"You should only rely on useMemo as a performance optimization. If your code doesnβt work without it, find the underlying problem and fix it first. Then you may add useMemo to improve performance."
It's not that complicated dude. You have a button and counter, if they need to interact, the parent should own the state not the children. If your dealing with a massive application, I dont know why you would care about the efficiency of a button rendering, but I guess if it had some expensive calculation in it you could useMemo to improve performance: dont forget the button rerenders many times already, when the user clicks and lifts thats 2. The function itself renders to in some situations, which is why you should never put functions in a react component, always externalze. Hierarchy is critical to react, just as it is to architecture, this is why it works so well.
Remember if your using useMemo for anything except performance, your just doing it wrong per react docs; you have a bug and your basically ignoring it with a hack, bypassing exactly what react is designed to help you identify. If you really have an app where you want a global state only, use redux, but its rarely the right decision... because local state does exist in real world physics, which computer interfaces are modelled after.
Usually when I meet someone with your attitude towards react, they are a backend engineer that is trying to unload all the broken data structures on the front-end to redo the ETL and creating chaos. React state is not for data, it is for frontend state, it is necessary... if you desire to feed data directly instead, you should be using stateless components and global state... but one doesn't build an app for efficiency like this, efficiency is achieved at the component level and how components are integrated, same in angular, same pitfalls there if you ignore the basics... it sounds like you want the framework to do that for you... maybe angular is better for you, but there are tradeoffs. You lose the architectural advantage of thinking in components, moving to the Producer model and traditional templates, any producer can serve any template, but only a few are compatible in regards to the data it needs... been years since I choose angular for a project so im rusty but I like it. Really the only difference between react and angular, with react you have the OPTION to lock templates and state together, so they are used correctly, one doesn't have to go identify the right template, it's there. All these frame works are doing is that, association state/producer to components/templates, the differences are trivial to me.
Anyway react is used for component composition, components that need state need state, if they don't they should be stateless. Your not going to convince me that componentization isn't a valid way to build a website, lol, nor could some one say producer template is invalid, nor event or callbacks... its all in how it is done... I agree I see companies screw up react more often than angular, but that is a skill problem with the framework... the crap I've seen... why I hate this article, these tips encourage incorrect use of react.
There are hundreds of libraries with well built components, just use that.
I have 20 years experience as a PE Software Engineer. 8 years with react, 5 angular and the rest of my time was pure JS and many other languages before this stuff was around or I had any desire to use it... since you question my abilities.
"The illustration I provided was when you have hundreds of these buttons and they all re-render due to a common state"
"The button problem was a simple way to illustrate scalability issue with the way react manages state."
"And no you canβt move the callback outside of components, because it relies on the current count to increment it."
You mention signalsJS. It works excellent with react, it is not an alternative but a compliment to it, just like redux. There is no magic library, it's all JS under the hood, these libs only exist to make devs life easier... your hatred of react is misguided, you have been using it wrong 10 years. Never fight a framework, if you cant accept the vendors motives, find another... I prefer react to angular, I went react when angular went CLI if I recall.
As far as I know, most of the other libs you mention like vite, svelt, preact are entirely built off of or modelled after react for slightly different use cases. I use vite a lot these days, vite is not a replacement for react my friend, in essence it's a replacement for create react app. Svelt I wasn't a fan of, too far removed from all other frontend frameworks imho for no real reason, the Ruby of frontend frameworks, but onky played with it 1 month... I prefer using raw events when I use events, didnt feel like there was much in svelt to help with good frontend architectural enforement, the things you have in react. As I recall, it's been a while yet, Vue was template management only and has nothing to do with states, but its been a long while.
"Vue doesnβt need the thousands of abandoned react component libraries, because itβs extremely simple to create any component on your own."
Try react+signals... it does work well... it just takes away most of the value in react imho... it basically replaces your state with events and reacts virtual dom, turning react into Vue if you prefer... redux does the same in effect if onky using global state.
Buttons rerendor constantly, any time a property changes, normal and virtual dom. It's so obvious your using it wrong... your worrying about optimizing a button with useMemo because you don't want to componentize your code, which is how react optimizes the code for you, if done correctly... any challenge you get, in any modern and well accepted framework, is always a matter of knowledge and skill... react ain't going anywhere.
I'm not bashing any of these other frameworks, fundamentally they only exist to help the dev, it's all 1s and 0s, and they all do equally well in equally different ways.
I have nothing to prove, lol, I'm just trying to help you. There are no frameworks I hate that's your thing.
Regardless, yes react and signals together does break react stste, it is intended to replace it in this case, just as event handlers do, only react knows it's dom without a useRef. Like I said, signals is a replacement for react state.
You can take react, externalize state to the top with redux or entirely altogether with events, with or without signals to make life easier. You can also externalize all jsx as templates so any can be used in any component like angular... you've effectively modelled angular philosophy with react and signals... perfectly valid stack. Examples a plenty even in the signals doc... I'm pretty sure you can even use preact signals with react. Never claimed to have built a big app with signals... like I said, I love what react offers just as much as angular, differences are trivial, how it gets used is more important... and I'm not impressed by this article or your examples sir. Take care, Tata.
You dont use Useffect and Usestate for everything. A junior developer does that. You only use a UseEffect when you really need to refresh! Eg. getting something from API. The way you do things will refresh everything. You dont see the difference in a small app, but in a big one you do! Even if the app is small you dont use UseEffect for everything its not an excuse to get away with it. That is what they dont teach you in most tutorials.
Yep, things should load asynchronous in react. API call with set state as callback, state change triggers useEffect which does any necessary calcs, template updates... component composition. Very standard. Not much different in angular when used right. Anyway, take care.
Yep, 2 ;o)
Are you the cause of all those applications that need to render every state change twice, because you setState in useEffect? π
Haha, good point! Your right, just pass the setter into the ajax callback; then trigger the ajax callback from useEffect on some user action or timer (which you know is gonna cause a rerender anyway). All that being said, I think react does always render twice for some reason... strict mode and dev mode, supposed to help devs catch bugs or something.
Regardless, these performance hits are completely negligable at any scale with proper async architecture... yes I've seen react apps that load in 20 seconds, seen the same with angular... has nothing to do with the framework, always architecture flaws from fighting frameworks.
Sorry programming in paragraph form, never my strongest ability.
In strict mode your components get mounted twice yes to help you catch side effects you forgot to cleanup in useEffect like removing an event listener
I think what you're taking about is React compiler and it's still in beta phase. It will handle all the performance stuff using some predefined memo techniques.
And I read somewhere that it will take some time to become stable and used in prod.
Why are you using them?
To ensure you don't pass callbacks and state to a useEffect that will have a different reference every time the render function is called? Thus constantly triggering your effect even though nothing actually changed.
It is very important, that second param list of useEffect. I see how a lot of programmers set it... they don't understand the component yet and they are just scraping for a variable to monitor to tie it to. It is important. Big differences if you have 1 useEffect in a component tied to 20 states or 20 useEffects tied to 20 different effects... just like any state machine, state must be engineered correctly... it is specifically frontend rendering state we are talking about, not db state or api or real data state.
useMemo is evil IMHO.
The biggest problem I see with poor rendering performance in react is that people are trying to tie huge dataststructures to the lowest level components... yeah, if 1 variable in the json changes, a lot is going to update... react state is not for data, it is for frontend state... if you have a rendering issue, it's poorly designed components or bad datastructures or both causing compounding issues.
Exactly
Useful hooks, thanks for sharing!
Im surprised there is no more comments like this tbh. This article is just a "Hey ChatGPT - make an article about React" kind of article. I mean - what kind article about React start with about knowing useState? Like its literally the first thing you learn and not some hidden gem. It's just all the most common React hooks straight out of the documentation.
If this article should have any value it could have been 7 custom hooks that is good to know. But this is just trash and feels like somebody who just want to have a lot of articles on his name.
Thank you for your feedback. My goal with this post was to help beginners who are just stepping into the React world, which is why I covered the fundamental hooks first. And honestly, if even one person finds my blog helpful, that makes me really happy. π Thanks again for your input!
I understand all of these hooks.
Thanks for your post βΊοΈ
Amazing πͺ
Such articles are such a noise and overflooding the internet...
Some comments may only be visible to logged-in visitors. Sign in to view all comments.