Beginner’s Guide to React Hooks

Rey
6 min readNov 7, 2020

By now, you might have probably heard of React Hooks which has been around for nearly two years since the release of React version 16.8.0. If you’re already familiar with react classes you are sure to embrace hooks. So, what exactly does it do, how do you use it?

Well, this article will provide you with the answers. Stay hooked!

Long before react hooks came into the picture, react classes were used in adding state to function components, however, these posed some issues like verbosity, increased complexity and, difficulty in testing. React Hooks are special functions that support local state management, in other words, it allows function components to have a local state which can change during the component’s lifecycle. One of the basic hooks this article will focus on is the useState() also known as ‘State hooks’.

useState() with an Integer

Let’s take a look at this simple example,

After importing {useState}, the App component shows the useState function call with an argument zero,

const [counter, setCounter] = useState(0)

this initializes the component state with a value of zero. The useState function returns an array with two variables, counter aka as the local ‘state variable’ and setCounter by using the array destructuring assignment syntax that enables unpacking values from arrays into distinct variables.

To begin with, the counter variable holds the initial value of the useState argument which is zero, depending on your needs, the type of variable can be a string, an integer, a boolean, an array or even an object. The setCounter is a state-modifying function that shall trigger a component re-render and thus cause an update to the corresponding counter variable in this case.

Let us look into this a bit further.

When the button click event is called, the setCounter function is invoked with the incremented counter value,

<button onClick={() => setCounter(counter + 1)}>

this function execution causes the App component to re-render itself where the useState function gets executed and thus updating the counter variable to one. Take a look at the simple flow below to picture the events again.

button click() → setCounter( counter+ 1) → Re-render component → useState(1) → counter displays 1

There’s more we could do with hooks.

Currently, our application uses a single state, however, hooks allow for multiple pieces of state within the same component by using the useState function multiple times as shown in the code below.

Hitting either this 👍 or this 👎 will cause the state of the component to re-render with the updated rating as shown below.

Image 1

useState() with an Object

Another method to achieve the same results is by passing an object argument to the useState.

In this example, a single useState is initialized where the state variables in the previous example are presented as object properties. The setRating function is handled from the event handlers where the new object is set using object spread syntax.

useState() with an Array

We can insert one more useState function with the rest to display the total ratings as shown below. For the purpose of testing other types of state variable, I have used an array this time. The setClick function sits within both event handlers and every time it gets called the setClick function triggers a component re-render and thus the click array increases in size.

.....
const [clicks, setClicks] = useState([])
const handleLikes = () =>{
setClicks(clicks.concat(‘Y’))
setLike(like + 1)
}
const handleUnlikes = () =>{
setClicks(clicks.concat(‘N’))
setUnlike(unlike + 1)
}
return(
....
<p>Total clicks : {clicks.length}</p>
....
)

Rules of Hooks

There are a few rules we must stick to in order to use state hooks correctly.

Hooks must strictly be inside the body of a react function component. The react hooks documentation explains it as follows,

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

Secondly, hooks should not be called from regular Javascript functions but rather through react components or custom hooks.

useEffects()

Next, we’ll take a look at another built-in hook called the useEffect().

During component rendering we may desire some side effects or operations to take place. Let’s see what the official document says about this.

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

useEffects can hold two arguments, the first being the desired effect or action to be executed and the second determines how often the useEffect should execute itself.

Let’s take a look at this example that uses useEffect for data fetching.

The first example shows a useEffect that executes a function to fetch data from a url from a json server. Notice that it also has a second parameter which is an empty array, in such a case our effect shall run only when the component is rendered the first time,

useEffect(function,[])

hence after the first render the ‘users’ array gets populated. Anything that would cause a consequent component re-render would not trigger this useEffect again. The result is shown below,

Image 2: Fetching users data

If the second argument does not exist, then the useEffect shall execute after each and every re-render.

useEffect(function)

For example, notice the second useEffect in the code below,

Every time ‘Count’ is clicked, a state change occurs and the component gets re-rendered during which the alert useEffect gets executed. In addition, when the ‘Set name’ button is clicked a state change occurs, the component gets re-rendered and the same alert useEffect gets executed again proving that an absence of a second parameter in useEffect would cause it to run after every re-render.

If you need to limit the frequency of the execution of a useEffect we could restrict with a second argument like [name] so that the useEffect gets called only when the [name] variables changes.

useEffect(function,[name])

For example, notice the last useEffect in the code body,

The last useEffect has a second argument with the state variable name as a parameter, whenever a new name variable is set, the state changes and the respective useEffect with name as a parameter gets called, during which the alert with the name is displayed. The result is shown below,

During the same rendering instance the ‘count useEffect’ gets executed too since it is meant to execute every time irrespective of the cause of the render. However, clicking the ‘Count’ button does not in turn trigger the useEffect with name parameter as this is meant to be executed only when name changes. In this way hooks allow for conditional triggering of useEffects.

Remember that useEffects should reside in the function component body.

I suggest you try out the codes in the example and print a few console.logs to help you gain an understanding of the order of execution.

The two types of hooks that the article describes are just to give you a basic understanding of React hooks. Apart from these, there other types of hooks, which you can read here in the official document.

Happy Coding!

--

--