Go Fish: Functional State with React Hooks 🎣

Image of a fish hook. So original right?
Image of a fish hook. So original right?

Why use Hooks?

Class components aren’t going anywhere so the old way of working with is still completely legitimate. So why is everyone telling you to hop on the bandwagon and start using hooks instead?

  1. Reduce the need for more than one type of component (no more class components)
  2. Save time refactoring components to add state
  3. Make components more readable
  4. Break application logic into reusable peices (custom hooks)
  5. No more dealing with the intricacies of the JavaScript ‘this’ object

Implementing State with Hooks

Two general things on how to implement hooks before diving into specific hook types. First, only use hooks in functions, not in class components. Hooks let up ‘hook into stateful React in functional components that were previously only accessible in classes. Second, you should use hooks inside loops or recursive functions.

Common Types of Hooks

The useState hook is called to add state to a function component. It returns the state, and a method to change the state. Here’s an example from the official React guides to look at:

import React, { useState } from 'react';function CounterExample() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

To use the useState hook, you first have to declare it. Typically it's destructed like this in the example. The first item in the array is state and can be given a variable like this one ‘count’. The second item in the array gives you a method to change the state, which you can also name, like ‘setCount’. useState takes one arguement which sets the value of the state. We are setting the initial count to 0 for 0 clicks.

The useEffect hook takes the place of “side effect” operations that we can perform based on the component lifecycle like componentDidMount, componentDidUpdate , and componentWillUnmount methods in React classes. A popular use case of the useEffect hook is to fetch data upon rendering a component. Here’s a look at the same example using the useEffect hook:

import React, { useState, useEffect } from 'react';function CounterExample() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

In this example, when the component was mounted, the useEffect hook set the document title to include the state of the count.

Custom hooks let you extract component logic into reusable functions. In order to share stateful logic before hooks came around, we used higher-order-components, or passed props between components. From the React docs, “A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.” Because components are also functions, we can create a custom hook that looks exactly like a component, except, instead of returning JSX, we are returning the result of the function. Custom hooks can use other hooks to return a result. Let’s look at another example from the React docs:

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID,
handleStatusChange);
};
});

return isOnline;
}

The first thing you notice about this is that it looks just like a functional React component! The key difference between a custom hook and a component is that a component returns jsx to add to the DOM, while a custom hook is a function that can be imported to any function and used throught the application without passing any props. Let’s looks at an example of using a custom hook:

import React from 'react';
import useFriendStatus from ‘./useFriendStatus’;
function FriendListItem(props) {
const isOnline = useFriendStatus(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}

I hope this demystifyed hooks for you, especially custom hooks (they’re just functions!!) As always, thanks for reading 🦜

Resources:

Written by

Full-Stack Software Engineer, Designer, and salsa dancer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store