Course Content
React Tutorial
React Tutorial
useEffect()
useEffect
is a hook in React that allows you to perform side effects in function components. It is a way to express side effects in a functional, declarative way, rather than using imperative code.
Here's an example of how to use useEffect
:
The function passed to useEffect
is called the "effect function". It will be called after the component is rendered. You can think of it as a combination of componentDidMount
, componentDidUpdate
, and componentWillUnmount
in a class-based component.
You can also specify when the effect function should be called by passing a second argument to useEffect
. This argument is called the "dependencies array". If you pass an empty array ([])
, the effect function will only be called once, after the initial render. If you pass an array of values, the effect function will be called anytime one of those values changes.
In this example, the effect function updates the document title
whenever the count
value changes. This is useful for updating the UI based on some state.
There are a few nuances to be aware of when using useEffect
:
-
The effect function should be pure, meaning it should not have any side effects other than the ones you explicitly specify.
-
The effect function should not cause any updates to the component state. If you need to update the state based on an effect, use a
useLayoutEffect
hook instead. -
The effect function will be called every time the component is rendered, not just on the initial render. If you want to perform an effect only on the initial render, you can use the
[]
dependency array to achieve this. -
If you don't specify a dependencies array, the effect function will be called on every render. This can be expensive and may cause performance issues, so it's important to be selective about which values you include in the dependencies array.
Thanks for your feedback!