📜  react hooks useeffect - Javascript (1)

📅  最后修改于: 2023-12-03 15:04:48.555000             🧑  作者: Mango

React Hooks useEffect

React Hooks useEffect is a powerful function used in React functional components to perform side effects such as fetching data, modifying the DOM, or subscribing to events. It behaves similarly to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.

How to use?

The useEffect function takes two arguments: a function that performs the side effect, and a dependency array that determines when this effect should be triggered.

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    // Perform side effect here
  }, []); // Empty dependency array means the effect only runs once on mount
  return <div>Example Component</div>;
}

In this example, the empty array [] passed as the second argument means that the effect will only run once when the component mounts. If we add a variable to the dependency array, the effect will run again whenever that variable changes.

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

function Example() {
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    // Perform side effect here
  }, [count]); // Will re-run effect whenever count changes
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Clean-up function

Sometimes we need to perform some clean-up operations before the component unmounts or before the effect runs again. We can do this by returning a clean-up function from the effect.

useEffect(() => {
  // Perform side effect here
  
  return () => {
    // Perform clean-up operations here
  };
}, []);
Dependencies and Performance

The dependency array is crucial for performance optimization. If we omit the dependency array, the effect runs on every render. If we have too many dependencies, the effect will run unnecessarily too many times. We need to find the right balance.

useEffect(() => {
  // Perform side effect here
  
  return () => {
    // Perform clean-up operations here
  };
}, [dependency1, dependency2, ...]);
Conclusion

useEffect is an essential function in React Hooks. It allows us to perform side effects in functional components and replaces the lifecycle methods used in class components. To use it effectively, we need to understand the dependency array and how to optimize for performance.