Go Fish: Functional State with React Hooks šŸŽ£

Lydia Gregory
3 min readOct 30, 2020
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 not use hooks inside loops or recursive functions.

Common Types of Hooks

1. The State Hook

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.

2. The Use Effect Hook

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.

3. The Custom Hook

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:

--

--

Lydia Gregory

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