DON’T MISS IT
REACT
USE EFFECT
HOOK
Understanding
useEffect Hook
The useEffect hook allows you to perform side
effects in your functional components.
Side effects are operations that affect
something outside the scope of the function,
such as data fetching, subscriptions, or
manually changing the DOM.
The useEffect hook lets you run code after the
component renders and clean up effects
when the component unmounts.
We import the useEffect and useState hooks
from React.
We use useState to create a state variable
data initialized to null.
We call useEffect with a function that fetches
data from an API. The empty dependency
array [] ensures the effect runs only once after
the initial render.
Inside the effect, we define an asynchronous
function fetchData that fetches data from an
API and updates the state with the fetched
data using setData.
We conditionally render the fetched data or a
loading message based on the data state.
Points to Remember
about useEffect
The second argument to useEffect is the
dependency array.
If you include variables in the array, the effect
will re-run whenever those variables change.
It determines when the effect should run. An
empty array [] means the effect runs only once
after the initial render.
Points to Remember
about useEffect
You can return a function from the effect to
clean up after it.
This is useful for removing subscriptions or
cancelling network requests to prevent
memory leaks.
Benefits of useEffect
Manages operations that affect things outside
the component, like API calls or subscriptions.
Encourages the use of functional
components, promoting a cleaner and more
concise codebase.
Provides a simple yet powerful way to perform
operations after render and handle cleanup.
DID
YOU FIND
IT
HELPFUL ?
Share this with a friend who needs it!
VINCENT RAJA
FULL STACK WEB DEVELOPER