Using basic Hooks in React

Melinda Diaz
The Startup
Published in
5 min readNov 17, 2020

There seem to be an endless number of ways to write the same things in code, and React is no different —like writing functional components vs class components, putting your export statements before the component name or after the entire function…It’s very confusing when you’re first starting out!

Well, I’m here to show you yet another way of writing the same thing in a different way. But I promise hooks are worth the learning curve — they will make your code much cleaner and more readable.

So what are these hooks?

Hooks

Hooks allow you to use state without writing class components.

What does this even really mean for our code? There are actually several different types of hooks, and they each have their own special functionality, like making sure a component only re-renders if a certain state is changed.

Functional Components

First, let’s look at how we can change our Class components into functional components:

Class Component:import React, { Component } from "react";

class Stuff extends Component {

// state constructor would go here
render() {
return (
<div>

</div>
);
}
}

export default Stuff

Can instead be written:

Functional Component:import React from "react";

const Stuff = props => (
// hooks will go here return ( <div>

</div>
)

export default Stuff

Alright — this makes it a little cleaner! But is it enough to make it worth learning hooks? You betcha — let’s start by looking at how the useState hook can help us with — you guessed it — using state.

useState

*To use hooks, you’ll need to import each one in the document(s) you use them in:

import React, { useState } from 'react'

Original React had you writing this clunky function:

constructor()
super()
this.state = {
count: 0
}

But hooks really clean this up:

const [count, setCount] = useState(0)

*This syntax will be the same when creating each new state, so all you have to change each time is what’s defined in bold.

This neat little package creates a new state called ‘count’, sets that initial state to 0, and names the function that will set the state (‘setCount’).

Now when you need to change the state in your code, you can use the newly created setCount function:

<button onClick={()=> setCount(count + 1)}

And that’s it! No setState function call-backs necessary.

Also, because you named it as a constant variable, you no longer need to use this.state — you can just use the variable name:

t̶h̶i̶s̶.̶s̶t̶a̶t̶e̶.̶c̶o̶u̶n̶t̶    →    count

useEffect

import React, { useState, useEffect } from 'react'

The useEffect hook is amazing — it effectively replaces componentDidMount, componentDidUpdate, and componentWillUnmount.

It accomplishes this by running every time the component is rendered — such as when state is changed — and only depending on the dependencies you set.

Here’s what it looks like:

useEffect(function thatDoesSomething, [dependencies])

Since useEffect is so great for running fetch calls, let’s use that for our example. Let’s say we want to have a number on our page that changes color every time it increments or decrements.

You could technically write your fetch call inside the useEffect function, but it’s much cleaner to create it in another function first.

const getColor = () => { 
fetch(http://www.fakeColorApi.com/randomColor)
.then(res => res.json())
.then(color => return color)
}
const [count, setCount] = useState(0)
const [color, setColor] = useState(null)
useEffect(getColor, [count])

The first argument (getColor) is the function we want to call, and the second argument [count] is an array of dependencies — here, we make the count state our dependency, so the useEffect hook will only run if the count state is changed.

*If you want your useEffect to run every time the page re-renders without having a dependency, you can call it with an empty array of dependencies:

useEffect(function something, [])

Just be sure the function you’re calling doesn’t update state, as this would cause it to go into an endless loop of being called!

useRef

import React, { useState, useRef } from 'react'

The useRef hook allows you to access DOM elements by adding a ref attribute to their tag, then calling the hook to change the element in other functions.

You start by adding the attribute to the html tag, naming it appropriately for your tag:

<button ref={buttonEl} wasClicked={clicked?}> Click me! </button>

Now, create a variable (outside of your return, where your hooks go), that sets that useRef instance:

const buttonEl = useRef()

This function then sets a .current property to the object’s corresponding Dom node — so buttonEl.current would return the entire <button> element. Then you can manipulate it in some way. For instance, our button example above has an attribute wasClicked, set to the clicked? state — here we could set a state so that if the user clicks the button (and we change the clicked? state to ‘true’) , the inner html would be updated:

changeButton = () => {   if (clicked? === true){
buttonEl.current.innerHTML = "I've been clicked!"
}
}

More Hooks

Here’s a list of the react hooks and a link to the docs if you want to check them all out:

  • useState
  • useEffect
  • useContext
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue
  • *custom hook

--

--