React Best Practices: useEffect Hook

Reading Time: 4 minutes

By using useEffect Hook, you tell React that your component needs to do something after rendering. This hook manages side-effects in functional components. Read this article to understand how its best practices will help you to build better React applications.

 

 

About this article

UseEffect hook is one of the most used effects in React, but new developers often get confused about when and how to use it. In this article, we will discuss the use of useEffect hook in React.

React useEffect hook is one of the most important hooks in React. It is used to perform side effects in functional components. It is a combination of componentDidMount, componentDidUpdate, and componentWillUnmount. It is used to fetch data from the server, subscribe to events, etc.

React useEffect, one of the most important hooks in React, is used to perform side effects in functional components. If we understand its best practices, it will help us to build better React applications 😉. Click To Tweet

The useEffect hook takes a function as an argument. This function is called after every render. The function can return a cleanup function. The cleanup function is called before the next render. The cleanup function is used to cancel the side effect.

Also, the useEffect hook takes a second argument. This argument is an array of values. The function is called only when one of the values in the array changes. If the array is empty, the function is called only once after the first render. If the array is not passed, the function is called after every render.

When does useEffect run?

Simple: The useEffect hook runs after every render.

How to use useEffect?

const [count, setCount] = useState(0);
useEffect(function() {
    document.title = <code>You clicked ${count} times</code>;
});

This is a very basic example of useEffect. The function is called after every render. But you may not want to run the function after every render. You may want to run the function only when the count changes. You can do this by passing an array of values as the second argument. The second argument is called a dependency array.

So, it is highly recommended to pass the dependency array to useEffect. If you do not pass the dependency array, the function is called after every render. This would not be considered a good practice.

How dependencies work in useEffect?

const [count, setCount] = useState(0);
useEffect(function() {
    document.title = <code>You clicked ${count} times</code>;
}, [count]);

The second argument is an array of values. The function is called only when one of the values in the array changes. If the array is empty, the function is called only once after the first render. If the array is not passed, the function is called after every render.

 

 

More on dependencies

The useEffect hook takes a second argument. This argument is an array of values. The function is called only when one of the values in the array changes. If the array is empty, the function is called only once after the first render. If the array is not passed, the function is called after every render.

So, for example, if you want to fetch data from the server only at loading time, you can pass an empty array as the second argument. The function is called only once after the first render.

useEffect(function() {
    fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response = response.json())
    .then(json = console.log(json));
}, []);

Primitive dependency

A primitive dependency is a dependency that is not an object or an array. For example, a string, a number, a boolean, etc. Primitive dependencies are compared by value. So if the value of the dependency changes, the function is called. If the value of the dependency does not change, the function is not called.

useEffect(function() {
    console.log("Hello");
}, ["Hello"]);

Non primitive dependency

A non-primitive dependency is a dependency that is not a primitive value like the ones in the previous section. For example, an array, an object, a function, etc. These non-primitive dependencies are compared by reference. So if the reference of the dependency changes, the function is called. If the reference of the dependency does not change, the function is not called.

useEffect(function() {
    console.log("Hello");
}, [function() {}]);
useEffect(function() {
    console.log("Hello");
}, [{}]);

State dependency

A state dependency is a dependency that is a state. The function is called only when the value of the state changes. If the value of the state does not change, the function is not called.

const [count, setCount] = useState(0);
useEffect(function() {
    console.log("Hello");
}, [count]);

How to cancel a side effect?

The useEffect hook returns a cleanup function. The cleanup function is called before the next render. The cleanup function is used to cancel the side effect.

const [posts, setPosts] = useState([]);
useEffect(function() {
    fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(json => setPosts(json));
}, []);

This is a problem. If the component is unmounted before the fetch is completed, the component will try to set the state of an unmounted component. This will cause an error. In order to fix this, we can return a cleanup function from the useEffect hook.

const [posts, setPosts] = useState([]);
useEffect(function() {
    fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(json => setPosts(json));
    return function() {
        console.log("Cleanup");
    }
}, []);

This would cover the best practices of useEffect hook. It is common to see useEffect hook used incorrectly. So it is important to understand how to use it correctly.

What other misuses of useEffect hook have you seen? Let me know in the comments.

0 Shares:
You May Also Like
Read More

Best Custom Hooks

Reading Time: 3 minutes Learn how Custom Hooks can help you to solve specific problems in your React Projects. Here is a…
reactJS
Read More

ReactJS: Loops in JSX

Reading Time: 4 minutes Why React? Nowadays developers know that Javascript's world is constantly changing. Every day a new library, framework or…
Read More

An introduction to Rust

Reading Time: 4 minutes At MagmaLabs we always keep up to date by trying and using new technologies because of our client's…