,

UseEffect Hook with Condition: React Hooks Tutorial Part 2

Posted by

Tutorial #37: UseEffect Hook with Condition | React Hooks | UseEffect Part 2

Welcome to Tutorial #37 of our React Hooks series. In this tutorial, we will be exploring the use of the useEffect hook with conditions in React.

What is the useEffect hook?

The useEffect hook in React allows us to perform side effects in our functional components. Side effects can include data fetching, setting up subscriptions, and manually changing the DOM. The useEffect hook runs after every render, and it replaces the lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

Using the useEffect hook with a condition

Sometimes, we may want to execute the useEffect hook conditionally, based on certain variables or props. This can be achieved by providing a second argument to the useEffect hook, which is an array of dependencies. The useEffect hook will only run if any of the dependencies have changed.

“`
useEffect(() => {
// This code will run whenever the value of count changes
// Do something
}, [count]);
“`

In this example, the useEffect hook will only run when the value of the `count` variable changes.

Example:

“`jsx
import React, { useState, useEffect } from ‘react’;

function App() {
const [count, setCount] = useState(0);
const [isMounted, setIsMounted] = useState(true);

useEffect(() => {
if (isMounted) {
document.title = `Count: ${count}`;
}
// Clean up code here
return () => {
// Clean up code
};
}, [count, isMounted]);

return (

Count: {count}


);
}

export default App;
“`

In this example, the `useEffect` hook will only run when the `count` or `isMounted` variables change.

Conclusion

In this tutorial, we learned how to use the useEffect hook with conditions in React. This can help us optimize our applications by only running certain effects when necessary. We also saw how to clean up after the effects are no longer needed. I hope you found this tutorial helpful, and stay tuned for more React Hooks tutorials!