React useEffect hook
Chibuzor Ojukwu
Posted on January 8, 2023
React is a Javascript library for building user interfaces. It is the most popular Javascript library. This is not an article for learning react from scratch. If you intend to start from scratch, I recommend this youtube video. We will be discussing of one of the React hooks -> useEffect. In version 16.8 of React, hooks were added to react.
What to learn
What are react hooks?
Importance of react hook
Rules of hooks
Some other popular hooks
The Role of the useEffect hook
Conclusion
→ What are React hooks?
React hooks are functions that provides function components with access to states and other React features. They don’t work inside classes. Before the advent of React hooks, states can only be managed within class components and with some external libraries. But, since react hooks was introduced, class components have almost become unnecessary.
→ Importance of React hooks
Hooks allows you to reuse stateful logic without changing your component hierarchy. This means that with hooks you can remove stateful logic from a component so that it can be reused. This makes sharing Hooks among components easy.
Hooks makes our code organised, neat, readable and maintainable even when it scales. With the class component lifecycle, complex components become hard to understand. For example, the componentDidMount method mostly have a mix of unrelated logic, some data fetching might be performed in it and also in componentDidUpdate. Also, componentDidMount _method may contain mix of unrelated logic that sets up event listeners with clean up done in _componentWillUnmount method, having related code that changes together being split apart but completely unrelated code being put together in a single method. This can easily introduce bugs and inconsistencies.
Hooks makes testing stateful logic easy.
Hooks let you use more of React features without classes
→ Rules of hooks
Only call hooks at the top level of your code. Don’t call hooks inside a loop, conditional, or nested function.
Only call hooks from a React function component. Don’t call hooks inside a regular javascript function. You can call hooks in your custom hooks.
→ Some other popular hooks
There are quite a number of React hooks, but I will do my best to list the most commonly used ones. We won’t be discussing them in-depth because this article is about the useEffect hook.
useState→ It is used for managing states in a function component and to preserve it between renders. It returns a pair; the current state value and a function that updates it.
useEffect→ This is used for handling side effects (eg. Data fetching, event handling, changing DOM manually from React components etc) in function components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes combined together.
useReducer → Just like the _useState _hook, this is used for managing state but for more complex ones. It takes in a reducer function as its first parameter and an initial state value as its second parameter. It returns an array that holds its current state and a dispatch function to which you can pass an action and later invoke it.
useRef → This allows to directly create a reference to the DOM element in a functional component. It return a mutable ref object with a property of .current. It persists state between renders without causing a re-render.
useContext → To return the current value for a context
useCallback → It return a memorized version of a callback to prevent an unnecessary re-render of a child component.
→ The Role of the useEffect hook
Now, let’s have an in-depth understanding of the useEffect hook.
It provides the ability to perform side effects in function components. Side effects are anything that affect something outside the scope of the function being executed. for example, making an API call, subscribing to a listener, manually changing DOM from a function component, timers etc.
In a class component, side effects are handled inside of it lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. For instance, if you decide to set up a subscription, you will do that in componentDidMount method and cancel it in componentWillUnmount method. On the other hand, the useEffect hook can handle both setting up of the subscription, its update, and its cancellation.
Effects are declared inside the component, so they have access to its props and state. By default, React runs the effect after every render.
Let’s look at a use case
import React, {useState, useEffect} from "react"
const FriendStatusWithCounter = (props) => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
}, []);
const handleStatusChange = (status) => {
setIsOnline(status.isOnline);
}
return (
<button onClick={() => setCount(prevCount => prevCount + 1)}>Click</button>
)
}
From the above sample code, we have a FriendStatusWithCounter component with a count state initialized to 0, it is for keeping track of how many times we click the button. Noticed we introduced another hook called useState which I have briefly explained.
As you can see, we are accessing the document’s title which is outside the component to be executed, that’s why we are using the useEffect hook. For the second useEffect hook, we set up the chatApi subscription inside the hook’s function body (in componentDidMount method for a class component) and then cancel subscription inside the body of its return function (in componentWillUnmount method for a class component). The second parameter of the useEffect hook is an array that will contain the dependencies (e.g the count state) that should trigger the useEffect _any time it changes (in _componentDidUpdate method for a class component).
So, in summary;
useEffect(() => {
//componentDIdMount
//componentDidUpdate
return () => {
//componentWillUnmount
}
}, [//dependencies)
→ Conclusion
We have come to the end of this article. We were able to understand the basics of hooks and what you need to know about the _useEffect _hook. I hope you find this article helpful.
🙂 Happy coding </>
Posted on January 8, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.