React Hooks
Updated:
✒ Reference: React Docs
What are Hooks?
“Hook” is a feature added in React 16.8, which is a collection of JavaScript functions that allow you to “hook into” React features inside the existing function components. By using Hooks, you can reuse stateful logic without writing a class or changing the component hierarchy.
Rules of Hooks
-
Only call Hooks at the top level.
Hooks cannot be called inside loops, conditions, or nested functions. By using Hooks at the top level of the React function, you ensure that they are called in the same order each time a component renders. Only then React can correctly preserve the state of Hooks between multipleuseState
anduseEffect
calls. -
Only call Hooks from React functions.
Hooks can only be called from React function components or custom Hooks. By this, you ensure that all stateful logic in a component is clearly visible from its source code.
Using the state Hook
Function useState()
useState
is a Hook that lets you add React state in a function component. Calling useState
declares a state variable which is preserved between function calls. It takes the initial state as an argument, and returns a pair of values: the current state and a function that updates it. It creates the variable at the first call, and gives you the current state during the next renders. Array destructuring is used to declare two new variables (the current state and the function) because each varaible has a specific meaning. You can use multiple state variables! (Just declare another state with a different name)
import React, { useState } from 'react';
function Example() {
// Declare a state variable called "count", and set it to 0.
// Call setCount to update the current count.
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Reading and updating state
To display the current count in a class, you can use count
directly; to update the state, you call setCount()
.
<button onClick={() => setCount(count + 1)}>
Click me
</button>
<p>You clicked {count} times</p>
Using the Effect Hook
Function useEffect()
useEffect
is a Hook that lets you perform different kinds of side effects in a function component. You can tell React which function to run (which effect to make) after render, and React will call the effect after performing the DOM updates.
Because useEffect
is called inside the component, you can access the state variable right from the effect without a special API to read it. The function passed to useEffect
is different on every render, which ensures that the state value within the function is not stale.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Update the document title using the browser API
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Effects with cleanup
Effects such as Network requests, manual DOM mutations, and logging do not require a cleanup, because we can immediately forget about them after running them. However, some effects require cleanup to prevent memory leak; for example, we might want to set up a subscription to some external data source.
The effect below returns a cleanup mechanism. React cleans up effects from the previous render, which helps avoid bugs.
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
More built-in Hooks in React are explained in the React documentation: Link here!
Leave a comment