Go Fish: Functional State with React Hooks š£
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?
- Reduce the need for more than one type of component (no more class components)
- Save time refactoring components to add state
- Make components more readable
- Break application logic into reusable peices (custom hooks)
- 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: