DEV Community

Dan Greene
Dan Greene

Posted on

When React Hooks "just clicked" in my head 💡🤩

A lot of people writing React think that when they initialize a variable, it's going to stay that way every time.

For instance, let's imagine a very simple React component.

const Demo = ()=>{
  const name = 'Bob';

  return <div>Hello: {name}</div>
Enter fullscreen mode Exit fullscreen mode

You might come away thinking that the name variable will always be the same piece of memory no matter how many times the Demo component is rendered.

In reality, React calls that Demo function every time it renders the parent components that contain the Demo component.

Wait a second...

Yes, that means that name is going to be a new variable every time Demo is called (which is every time React needs to render it).

So, it's almost like each time Demo is rendered, the name property is born again. That realization is what helped make React Hooks click. Hooks lets you make name immortal (for the life of the browser tab being open).

What if I wanted it to stay the same?

Well, that's what hooks were more or less invented for. Hooks predominantly are about allowing React devs to use simple functions to describe their creational patterns but to allow these functions to express stateful concerns.

Before hooks, you would have had to use a Class to describe a component that has state.

But with React Hooks like useRef, you can say "hey React, would you mind keeping this variable around?"

K, but let me see this in action

Sure! Here's a demo that shows starts off showing how the Demo component is essentially stateless and therefore the name property can never be the same between renders.

If you follow along the comments in the code example below, you'll be able to uncomment the correct lines to show how you can inform React of which pieces you want it to keep the same between renders.

Top comments (2)

lexlohr profile image
Alex Lohr

It clicked with me when I researched the internals of the new fiber architecture, which is basically tree-walking over fiber nodes, which can be elements or hooks.

The whole architecture is based on memoization (call caching) and tree-walking during different cycles (mount, render, layout, unmount).

useRef(value) is basically useState(value)[0].
useCallback(fn, deps) is a shorthand for useMemo(() => fn, deps).
So you're left with useState, useMemo, useEffect and useLayoutEffect, the latter just being evaluated during different cycles.

rawas_aditya profile image
Aditya Rawas

In simple words react hooks has global variables that are same throughout applications, but other variables like useStates and variables are local and have a scope within components