Chris Staudinger
Chris Staudinger

@ChrisStaud

12 Tweets 7 reads Aug 30, 2022
📌 React’s 6 main hooks explained - Web development with React just got easier 🧵👇
In this thread, I’ll break down and provide illustrations of the six main hooks in React.js ⚛️
You will leave with a clear understanding of;
→ What each hook does? ⛓
→ Why to use each hook? 💡
React hooks were the death of class components 💀
Hooks were released in v16.8 and gave us access to all the features in class components but without so much boilerplate code🤮
It was a fresh breath of life for React.js, that changed web development to this day 🚀
1. useState() ⚛️
What is a hook? 🤔
A Hook is a special function that lets you “hook into” React features.
useState() is a Hook that lets you add React state to function components 🚀
1a) Why use useState() ?
→ To make UI interactive, you need to be able to trigger changes to your underlying data model or component. React achieves this with state 💡
→ The useState hook gives you a clean, concise method to work with state.
2. useEffect() ⚛️
Often we need to perform tasks known as “side effects” in React. Things like data fetching, subscriptions, or manually changing the DOM 🌟
We call these operations “side effects” because they can affect other components and can’t be done during rendering 💡
2a) useEffect() runs after every render.
React can skip an effect if certain values haven’t changed between re-renders. To do so, pass an [] as an optional 2nd argument 🙌
There is also an optional cleanup function to unsubscribe any subscriptions & not introduce memory leaks.
3. useMemo() ⚛️
Some functions can be very expensive to call 💰
Sometimes we don’t want a function to run every render, only when a certain value changes.
That’s where useMemo() comes in.
It will only recompute the memoized value when one of the dependencies has changed 🚀
4. useCallback() ⚛️
Works the exact same way as useMemo().
Except it returns a memoized callback (not a memoized value) ✨
5. useContext() ⚛️
There are often times where multiple components need access to the same value.
The cleanest way to do this is with context.
Context provides a set of values to all components consuming it 💯
6. useReducer() ⚛️
useReducer() is another way to update.
It can be preferable to the useState() when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
It is the pattern the Redux uses for state management ✨
That's a wrap!
If you enjoyed this thread, don’t forget to like, comment, and retweet the first tweet!
I create threads, and hand-drawn illustrations to level up your software development game 🚀 🧵 🎨
Follow @ChrisStaud
for more free tips and free resources.

Loading suggestions...