A gentle introduction to React hooks
23 Sep 2019 - John
One of the very early blocks for new React developers is the use of class components. Specifically, the use of the this
keyword might prove confusing. Aside from that, the use of class components leads to a lot of boilerplate code that does little to help the readability of our code.
This is why functional components were introduced to React. They allow us to accomplish the same functionality while at the same time reducing the need to write so much boilerplate code. So a component can go from this:
import React, { Component } from 'react'
class myComponent extends Component {
render() {
return (
<div>
<h1>This is a class component</h1>
</div>
)
}
}
export default myComponent;
To this:
import React from 'react'
export default function myComponent() {
return (
<div>
<h1>This is a functional component</h1>
</div>
)
}
This is great! Not only did we simplify a lot of our code, but we also accomplish the exact same thing. But wait a second, what if we need to use state or access the component lifecycle?
Enter React hooks
Hooks are a set of special functions that were introduced in React 16.8. They allow us to have access to both state and the component lifecycle inside functional components, which allows us to have the best of both worlds.
What hooks can we use?
While there are a few hooks, the most important one to start using is the useState
hook. This is the one that lets us have state, and it works like this:
- First import the hook along with React:
import React, { useState } from 'react'
- Then declare a new variable that is an array. This array will have two elements: the state itself and the name of the function we will use to update the state. Finally, we need to assign
useState()
along with our initial value while passing as an argument to it. This argument will be the initial value of our state. So in the past, if our state had a key called count that was updated withsetCount(value)
, we now do it like this:const [count, setCount] = useState(0);
An then you can define your
setCount()
function to do whatever you want it to do. In out case, if we wanted it to add 1 to our count key in the state, we wouldn’t do anything different than what we’ve been doing:function setCount() { setState(prevState => prevState + 1); }
Then you can call your
setCount()
function wherever you want. Easy peasy. Now what if we need to fetch some data oncomponentDidMount
?The useEffect() hook
In the past, we used to be able to use
componentDidMount
,componentDidUpdate
,shouldComponentUpdate
andcomponentWillUnmount
as separate phases of the component life cycle. With theuseEffect()
hook, we don’t need to worry about all of those since it takes care of everything. Let’s suppose we need to fetch a list of users. The first thing we need to do is import theuseEffect
hook along with React:import React, { useEffect } from 'react'; Then we set our state: const [users, setUsers] = useState([]); And then use our useEffect hook to fetch our users: useEffect(() => { function getUsers() { fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(data => setUsers(data)); } getUsers(); });
And with that, you have access to the users variable in your state.
Are there any more hooks?
Yes, there are. We only covered two of them, but there are more and they’re divided in two groups:
Basic hooks:
- useState
- useEffect
- useContext
Additional hooks:
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
- useLayoutEffect
- useDebugValue
Additional reading
While they seem kind of dauting at first, using hooks is actually pretty easy and will improve the quality of your code. I highly suggest you check React’s documentation on the subject and I promise you’ll be hooked in no time!