understanding react hooks
Tags: react, javascript, webdev, programming
Published: 2024-06-27 01:45:42

back in 2018, Sophie Alpert, Dan Abramov, and Ryan Florence did one of the most important talks of the history of web development.

they were at the ReactConf introducing the React Hooks to the developer community.

[React Today and Tomorrow and 90% Cleaner React With Hooks](https://www.youtube.com/watch?v=dpw9EHDh2bM)

## the motivation behind the creation of hooks

back in the day, react code used to look like this:

![OG react code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcb77so87ezqgq9vd6dw.png)

most of the react code was written using classes, so, its components were called class based components.

when you wanted for your application to be controlled and have states, you would need to make it a class, so a bunch of code should be added:
1. class extending a react component
2. a constructor with the component props
3. use super() to make the state and the props accessible through the component
4. bind all of the state writing methods

yeah, that's definitely a lot of unwanted code... the files were a mess and they used to have more then 1.000 lines

## the wrapper hell

Sophie and Dan made sure that the new react features would fix a well known react issue. it was called: wrapper hell

do you remember this image?

![wrapper hell code example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vu3r4ykskiobo2sog6uo.png)

yeah, this is wrapper hell

basically the OG react codes needed a lot of tags to access contexts, to display different themes, to get the users locale, etc.

and all of that was because the hooks did not existed - yet!

## finally: the hooks

three hooks were introduced back in the day: useEffect, useState and useContext, and all of them had unique purposes and functions.

### the useState

useState is the most used and some must say: must important react hook.

basically, useState is a hook used when you want to make sure that a component have a memory. when you want your component to store and remember a variable, you should have a state.

react applications are known for being personal and customizable since its very first beginning

> To me, Next is not just about making fast sites. It's about making sites that are personal. - **Guillermo Rauch, founder of Vercel and creator of Next.Js**

and the useState was a real game changer for the web development


![OG class based component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60r563zja64n26elg9tp.png)


I wrote this OG class based component -- probably is inaccurate -- in order to illustrate how react components looked like before the hooks.

![react component with hooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ts5yna5locioyptvwk3b.png)

this is a react component that uses the react 16.8 version -- the version where the hooks were introduced.

as you can see, it is really noticeable how much code was turned unnecessary after the hooks. our DX have increased considerably and the components were more succinct and readable.

if you don't know why we use states, please read [this](https://react.dev/learn/state-a-components-memory)

### the useEffect

have you ever heard the phrase "the component did mount"?

`componentDidMount()`, `componentWillUnmount()`, `componentDidUpdate()` were methods very much used on the earlier versions of react to listen and interact with different stages of the component rendering and compiling process

![react mounting methods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6khr7lni48t1pkfmo6m.png)

after the introduction of the "listener" hook, the useEffect, those methods were happily replaced

![first look at the useEffect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ouatm9r57djapqdonujx.png)

basically what the useEffect hook does at the code above is to listen to all of the changes on the page and change the width state value through the `setWidth` method.

the main purpose of the useEffect is to listen to changes and run subsequent functions, BUT, this hook is definitely the most MISUSED hook.

today we are used to use the useEffect hook to perform changes based on everything, and this may cause a lot of issues such as:
- infinite loops
- duplicated values inside state arrays
- unwanted code smell -- yeah, using a lot of useEffects should be considered as code smell

so, think about this: when you want something to change during a function, your first thought may look like this:

![user registration process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2bvv42f4ythi1av5ypwr.png)

but, a bad logic at the API gateway or the user registration process could lead to:


![useEffect unwanted behaviors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7xjw5sw5k19ern0qnfta.png)

but, there are some ways to fix it. this is the one I like the most:


![react user registration process with a callback function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ga0r9vg1ydgs0p76ekeu.png)

instead of dumping a lot of logic inside your useEffect and your other methods to try and force some kind of idempotency, you could just go and replace it by a callback function that handles and sets the state accordingly to the component's needs. as simple as that.

be careful with the way your component handles effects.

### useContext

the useContext is much easier to understand than the useEffect, because it has a lot to do with the useState.

basically, the useContext hook should be used to store global values or states

take a look at how contexts were managed before:

![old react context managing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vf49a7wyqr7apgg4py13.png)

and after the useContext hook, it started to look like this:

![refactored code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kov05fiq4n0c5bkgp987.png)

as you can see, now we can simply import the context and wrap it with the useContext hook. there is no need for the context consumers no more.

if you don't know why we use contexts, please read [this](https://react.dev/learn/passing-data-deeply-with-context)

## conclusion + custom hooks

really understanding the react hooks will make your code work and look really better. sometimes we get so used to write code without thinking that some basic concepts run out of our mind.

it is important to always remember of the react foundation when writing code.

the React Core team did not wanted our code to be static and boring, so that is why they developed a whole new community experience through the Custom Hooks.

I now the Next developers would not be able to live without a `useRouter()`, or a `useSearchParams()`. also, what would the new React developers do if they did not had the `useMemo()`?

if you don't know how to mix the concepts explored through this article and come up with a custom hook, just wait until I publish the next article showing you how to.

thanks for reading!

-------

Photo by <a href="https://unsplash.com/@oskaryil?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Oskar Yildiz</a> on <a href="https://unsplash.com/photos/flatlay-photography-of-desktop-gy08FXeM2L4?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>