Everything I Know About React Hooks

Ignas Butautas
The Startup
Published in
4 min readDec 15, 2020

It seems that hooks are all the rage these days. Therefore, I found it important to learn them myself. You’re probably reading this because you’re in the same shoes I’m in. Well young grasshopper, here’s what I know so far.

To start off, let’s talk about state. To get state in your functional component all you need to do is import it like so:

import React, { useState } from 'react';

It’s that easy you don’t need to download anything. When it comes implementation, it’s also pretty simple. Let’s say you had a form that had a user input information. For this example let’s say it’s an artist and a track. You’d need to store this information so that you can send it to an API, or do whatever you want with it. It’d look something like this:

const [ artist, setArtist ] = useState('');const [ track, setTrack ] = useState('');

Let’s go over what’s happening here. You are creating a variable that’s an array? Then you’re having it assigned to useState? I’ll explain myself, if you’re familiar with class components and how you assign state in there, it’d look like this:

state = {
artist: '',
track: ''
}

With hooks you are individually assigning each part of state to its own variable. So calling ‘artist’ within your functional component it’ll return the most recent state. The ‘useState’ part is essentially what you want the initial state of that variable to be. In my case just an empty string (because that’s all the information I need.) You can set your initial state to anything you want it to be:

const [ artist, setArtist ] = useState([{artist1: 'hi'}]);

That works to, but you just need to be conscious about what kind of information you’ll be trying to store. Let’s talk about the ‘setArtist’ part, when using hooks wording does matter. Prefixing the second argument with ‘set’ lets react know what the purpose of that variable is. When using ‘setArtist’ it’ll be treated pretty much like ‘this.setState’ but just more specific. Originally we would set state like this:

this.setState({
artist: 'fergie'
});

Now it’s trimmed down to look like:

setArtist('fergie')

Boom ezpz. To give some more ideas on functionality of this here’s a random example:

Let’s say you have button with a click listener, and everytime you wanted to click it, the count would increment by one.

const [ count, setCount ] = useState(0);const incrementCount = () => {
setCount(count + 1);
};
return (
<> // These are 'fragments' aka white space
<div>{count}</div>
<button onClick={incrementCount}>click me!</button>
</>
);
/// cleaner way to write this would beconst [ count, setCount ] = useState(0);return (
<>
<div>{count}</div>
<button onClick={() => setCount(count + 1)}>click me!</button>
</>
);

(Fragments are used so that you don’t have a million divs in your application for no reason)

A class component it would look something like this:

state = {
count: 0
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 })
}
render(){
return(
<>
<div>{this.state.count}</div>
<button onClick={this.incrementCount}>click me!</button>
</>
)
}

I hope that’s enough explanation about useState, if you’re still confused I’d recommend checking out this article.

On to next part, useEffect. Though you can get a lot done just with setState, useEffect gives your functional components a version of ‘lifecycle methods.’ To start off, let’s go over the most common one, componentDidMount. To have useEffect act like a componentDidMount you’d write it something like this:

import React, { useEffect } from 'react'useEffect(() => {
// insert thing you'd like to do on mount here
}, [])<-- dependency array

useEffect is a function that runs right when the component gets rendered. So if you’d like to make a fetch request, this is the place you’d want to do it. useEffect takes in an optional argument which is called a ‘dependency array.’ If you want to treat useEffect as a componentDidUpdate you would place the information that would constitute the need for change there. For example:

import React, { useState, useEffect } from 'react' const [ count, setCount] = useState(0)
useEffect(() => {
console.log('button has been clicked')
},[count])

Now everytime the count changes that useEffect will re-run. The dependency array can take in a bunch of arguments, and it watches for any changes. If any of those things in the dependency array change in any way, then it’ll re-run anything inside of it.

If you are using a dependency array you won't want to lie to it. If there’s a dependency, then you’ll need to add it in. Otherwise you’ll create bugs, or unintended consequences.

The last thing I’d like to touch on is mimicking componentWillUnmount. Let’s say you have a counter incrementing every second once the component mounts. It’d look something like this:

const [ count, setCount ] = useState(0)useEffect(() => {
let id = setInterval( setCount(count + 1), 1000)
return () => clearInterval(id)})

The crucial part here is to add a return statement of the things you’d like to cleanup. To put it in better words, “react performs the cleanup when the component unmounts… effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time” ( React docs.)

To wrap up, I know there’s more you can do with useEffect, and I am aware that there are more hooks like, useRef, useReducer, useCallback, and the ability to use custom hooks. But I have yet to get my hands on these tools. Once I do I promise I’ll report back everything I know. Thank you!

If you’re still confused, here’s an article that goes into the deep end about useEffect. https://overreacted.io/a-complete-guide-to-useeffect/

P.S — here’s a video for introduction to hooks

--

--

Ignas Butautas
The Startup

An aspiring coder, trying to make sense of The World (of coding.)