useEffect react

Understanding useEffect in React.js

If you're working on a React.js project, you may have come across the useEffect() hook. This hook allows you to perform side effects in functional components, such as fetching data, subscribing to events, or manipulating the DOM.

Let's take a closer look at how the useEffect() hook works and how it can be used in your React.js projects.

The Basics of useEffect

The useEffect() hook is called after every render of your component. It takes two arguments: a function to execute when the hook is called, and an array of dependencies that determine when the hook should be called.

Here's an example:


import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

In this example, we define a component that displays a count variable and a button to increment it. We also define an effect that updates the page title with the current count value.

The effect is only called when the count variable changes, thanks to the dependency array. This ensures that the effect only runs when it needs to.

Cleaning up Effects

Another feature of the useEffect() hook is the ability to clean up after your effects. This is useful for things like unsubscribing from events or canceling API requests.

The cleanup function is returned from the effect function and is called before the next effect is called, or when the component unmounts.

Here's an example:


import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const interval = setInterval(() => {
      console.log('Hello!');
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      {visible ? <p>Hello World!</p> : null}
      <button onClick={() => setVisible(!visible)}>Toggle</button>
    </div>
  );
}

In this example, we define a component that displays a message and a button to toggle its visibility. We also define an effect that logs a message every second using setInterval().

The cleanup function returned by the effect clears the interval when the component unmounts or the effect is re-run. This ensures that we don't have any memory leaks or console logs after our component is no longer in use.

Conclusion

The useEffect() hook is a powerful tool for managing side effects in your React.js projects. By understanding how it works and how to use it, you can make your components more efficient and prevent memory leaks.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe