- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React useEffect Hook
- useEffect is a React hook that enables performing side effects in functional components.
- It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.
Purpose
- Handles asynchronous operations, data fetching, subscriptions, or any side effects in functional components.
- Ensures that side effects do not cause performance issues or memory leaks.
Syntax
- Import useEffect from the 'react' library.
- Pass a function as the first argument, which will contain the code for the side effect.
- Optionally, provide a dependency array as the second argument to control when the effect runs.
Runs on every render
useEffect runs after every render without any specific dependencies.
Runs on first render
useEffect runs only on the first render with an empty dependency array.
Runs when data changes
useEffect runs when specific props or state values change.
Cleanup
- Use useEffect for cleanup operations, such as clearing intervals or canceling subscriptions.
Dependency Array
- The dependency array in useEffect determines when the effect runs.
- If the dependencies change between renders, the effect runs.
Effect without Cleanup
- If the effect doesn't require cleanup, you can omit the return statement.
Summary
useEffect is a powerful tool for managing side effects in functional components. It contributes to a cleaner and more efficient code structure in React applications.