Photo by Ilya Pavlov on Unsplash

Getting stuck into Hooks

Eliot Howes
Eliot’s Journey
4 min readOct 6, 2019

--

A short look into using Hooks in React

React Hooks were created to solve a few problems that come with using React. Using React in larger and more complicated apps can lead to some of the below issues:

  • It can be difficult to manage state and reuse stateful logic between components
  • Components become large and hard to manage and ultimately debug
  • Using classes in javascript can be a restrictive and challenging requiring an understanding of how ‘this’ works

The following post will look at how Hooks can help use to reuse stateful logic in different React components.

If you have created React apps you will notice that as your project gets bigger it can be difficult to manage state. You can find yourself feeling frustrated by having to pass state down from component to component and then call functions in other components to manipulate said state.

Perhaps you want to use the same state and logic in several different components…using React alone this tough if not impossible.

When building web apps we often find ourselves writing functions that we may use in lots of places for example a toggle function that will show or not show a component. This is a great example of when Hooks can help us hugely.

Take a look at this code:

import React from 'react'export default class FirstReactComponent extends React.Component {  state = {
toggle: false
}
updateToggle = () => {
this.setState({toggle: !this.state.toggle})
}
render() {
return (
<div>
<button onClick={updateToggle}>Toggle Component</button>
{this.state.toggle && <SecondReactComponent >}
</div>
)
}
}

Here we create a class FirstReactComponent and set an initial state toggle to the value false. We then render SecondReactComponent when the value of toggle is true and requiring another function updateToggle that sets the updates the value of toggle .

What happens when we then create another react component and again want to use a toggle — well we have to re-write the above code in another React class component. Isn’t that annoying and not very DRY/reusable.

Welcome Hooks…

Lets take a look at how we can recreate this the above code using the simplest form of hooks:

import React, { useState } from 'reactconst firstReactComponent = () => {const [toggle, setToggle] = useState(false)    return (
<div>
<button onClick={() => setToggle(!toggle)} >
Toggle Component
</button>
{toggle && <SecondReactComponent >}
</div>
)
}export default firstReactComponent

Ahhhh….isn’t that a lovely concise and easy to read component. No class in sight.

Let’s take a look at what’s going on here. We are importing useState a React function that returns 2 things, the current state and a function to update the current state.

We then destructure this and set initial state, in the case of our toggle function, to false. To see this in action vs the old way:

const [toggle, setToggle] = useState(false)state = {
toggle: false
}

Now rather than creating a new function to update our state we can just call the function setToggle and pass it the value we want to set our new state to:

setState(!toggle)updateToggle = () => {
this.setState({toggle: !this.state.toggle})
}

Ok great! We made our code more pretty and a bit easier to read…so what?

Well using destructuring we can set multiple different states for our component:

const [toggle, setToggle] = useState(false)
const [counter, setCounter] = useState(0)
const [searchTerm, setSearchTerm] = useState('')

Again, cool but I still don’t get what all the fuss is about. Introducing Custom Hooks!

Custom Hooks allow you to use the logic you have seen above but to create your own reusable Hooks. Let’s take a look at an example:

import { useState } from 'react'const useCounter = () => {  const [count, setCount] = useState(0)  const up = () => setCount(count + 1)   const down = () => setCount(count -1)  return [count, up, down]}export default useCounter;

Creating a custom Hook starts out the same, we import the function useState from React. We can now create our own function that uses state and can manipulate it in different ways.

Starting out in the same way we destructure useState and then we define two new functions for updating the state, up and down . One increments our state count the other decrements it. We then return and array (or object) containing our current state count and our two functions for manipulating it. We can now export this function and import it anywhere we want in our app and in as many different components as we like and each will be able to manage their own count.

……now I get it, thats pretty cool. Obviously this is a very simple example of a custom Hook but you can see from this how useful they could be in bigger apps, not having to pass state down as props, and not calling functions in one component to manipulate state in another.

This is just the start!! It gets better and in my next blog post I will explore some of the other features of Hooks and how awesome they are.

Until next time…

--

--

Eliot Howes
Eliot’s Journey

Personal and Technical blog about all things software development. Full Stack Software Developer - London.