Learn React Hooks with Theo

He said they also eschew the complexity of bringing in a state management library like Redux, instead opting to use React’s Built-in Tools. He recommended I learn to use hooks and start to move away from class components.

So I started learning about hooks, something I’d been postponing doing. FYI, in the course of writing this, I noticed I was essentially writing my own version of the React Docs page on Using the State Hook. So if you want to hear it direct from the horse’s mouth, there you go.

What Hooks allows us to do is to have functional components with state. The conventions are different of course from using this.setState as one would in a React class component. However, in what I’ve learned of hooks in the past 36 hours, I’m pleasantly surprised by how straightforward I’ve found this new methodology.

EXAMPLE OF THE useState() HOOK

const [coolData, setCoolData] = useState(‘initial cool piece of data’)

console.log(coolData) // => ‘initial cool piece of data’

// later, when we want to update this we invoke setCoolData like this:

setCoolData(‘I am a far cooler piece of data than that earlier one’)

console.log(coolData) // => ‘I am a far cooler piece of data than that earlier one’

EXPLANATION OF useState() HOOK

We can use destructuring assignment to capture the return value of useState (an array with two elements) as two separate variables.

The first variable, coolData, is simply initialized with the value of the argument passed to useState.

The second variable, setCoolData, is a function that allows us to update the first variable, while keeping React in the know (remember, never mutate state). So the second variable is essentially a single-variable version of the this.setState() method call we would use in a class component to update state.

One of the aspects of hooks that I’m still grappling with is where and how this information is being stored. I’m used to objects being used as storage vessels; my brain wants to imagine some global state/store object like in redux, an object that holds onto all these separate but component specific state variables.

But with hooks the advantage seems to be that the variable is simply saved on its own and by means of its association with the component that is using it. That makes enough sense, but it also doesn’t satisfy my visuospatial curiosity for WHERE the thing is being held and contained. I’d like to understand React at a deeper level to grasp how these variables are being stored.

For now, however, the best I can do is quote the React Docs explanation: How does React associate Hook calls with components?

‘There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.’

With my (currently) limited knowledge of data structures this sounds like they’re describing an array of objects, where the memory cells are objects (this is said explicitly in the quotation) and the array containing them is there but they haven’t named it (I’m assuming it is an array so I could be wrong).

Anyway, let’s move on and compare class components with state to function components with state via React Hooks. Let’s say our class component’s state looks like this:

state = {

coolData: ‘Initial cool piece of data’,

coolDude: ‘Sup brah’,

coolLady: `You’re dumb brah`,

coolPerson: ‘Remember Klondike bars?’,

coolFact: ‘Russian has two words for blue, one for dark and one for light blue’,

}

Let’s say a user submits new data to our app which should update coolData to “an even cooler piece of data, brah!” In a class component we could accomplish the update by writing:

this.setState({coolData: “an even cooler piece of data, brah!”}).

This actually merges the old and new state into an entirely new JS object, where the old coolData value is replaced with this new value.

I’ve tried writing a couple versions of explanations to why this is less efficient than singular updating of an individual state variable. However, I think this is the point where the responsible thing to do is to admit that I’m not entirely sure.

My sense is that issues can arise in React stateful class components when an individual property in state is updated. You’d like this to only affect components reading from the particular property of state. But sometimes, this causes rerendering of other components A) due to those components being tangentially connected to that property and/or B) due to the entire state object being updated.

If this latter point (B) is correct, then I would argue confidently that modularizing state via stateful variables with Hooks would improve performance. If only (A) is correct though, I would not be able to explain clearly how Hooks improves performance. Part of what is throwing me for a loop is React’s somewhat involved diffing process involving the Virtual DOM and Native DOM.

Perhaps the point is that it is really updating to the Virtual DOM that Hooks reduces/optimizes, since it sounds like optimization of Native DOM rendering/rerendering was one of the original strengths of React before Hooks existed (read: StackOverflow: ReactJS — Does render get called any time “setState” is called?).

HOWEVER, USING HOOKS, WE INITIALIZE STATE LIKE THIS

const [coolData, setCoolData] = useState(‘Initial cool piece of data’)

const [coolDude, setCoolDude] = useState(‘Sup brah’)

const [coolLady, setCoolLady] = useState(`You’re dumb brah`)

const [coolPerson, setCoolPerson] = useState(‘Remember Klondike bars?’)

const [coolFact, setCoolFact] = useState(‘Russian has two words for blue, one for dark and one for light blue’)

Each piece of state is separate and each has its own updater method.

Unresolved Questions and Further Reading

  • Is there any conflict of interest or confusion created by the JavaScript language using prototypal inheritance and React.js preferring composition to inheritance?
  • VDOM vs NDOM and the performance gains of using Hooks

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Theo Carney

Theo Carney

Software Engineer and Chinese Language Nerd