📌  相关文章
📜  useEffect(() => { console.log('foo') }, [bar, baz]) (1)

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

useEffect Hook

The useEffect hook is a built-in hook in React that allows you to perform side effects in function components. It is used to manage side effects, such as data fetching, subscriptions, or manually changing the DOM, that need to be performed after the component has rendered.

Syntax

The basic syntax of the useEffect hook is:

useEffect(() => {
  // Side effect code
}, [dependencies]);
  • The first parameter is a callback function that contains the side effect code.
  • The second parameter, dependencies, is an optional array that specifies the values that the effect depends on. If any of these values change, the effect will be re-run. If the dependencies array is omitted, the effect will run after every render.
Example
import React, { useEffect } from 'react';

function MyComponent({ bar, baz }) {
  useEffect(() => {
    console.log('foo');
    // Side effect code here
  }, [bar, baz]);

  return (
    // JSX code here
  );
}

In this example, the useEffect hook is used to log foo and perform some side effect code when either bar or baz changes.

Side Effects

Side effects are actions that are executed outside the scope of a component, such as fetching data from an API, subscribing to events, or manipulating the DOM directly. The useEffect hook provides a way to handle these side effects in a clean and controlled manner.

You can perform various side effects within the useEffect callback, such as:

  • Fetching data using AJAX calls.
  • Subscribing to events, like keyboard or mouse events.
  • Changing the document title.
  • Modifying the DOM directly.
Cleanup

The useEffect hook also allows you to specify a cleanup function that will be executed when the component is unmounted or when the dependencies change before re-running the effect. This can be useful for canceling subscriptions, removing event listeners, or cleaning up any resources created by the side effect.

useEffect(() => {
  // Side effect code here

  return () => {
    // Cleanup code here
  };
}, [dependencies]);
Conclusion

The useEffect hook is a powerful tool in React that allows you to handle side effects in function components. It provides a clean and declarative way to manage side effects, with the ability to control when the effects run and clean up after themselves. By using the useEffect hook, you can ensure that your components are efficient, maintainable, and free from memory leaks.