The useEffect
hook is used in React to perform side effects in functional components. useEffect
allows us to execute a function/component when certain dependencies change in the component. useEffect
takes two parameters, a function to execute and an array of dependencies (optional).
To use useEffect
, we first import it from react:
index.tsx42 chars2 lines
Once we have imported it, we use it in our functional component like so:
index.tsx337 chars17 lines
In this example, we have created a simple state variable count
using the useState
hook. We then use the useEffect
hook to execute some code when the count
variable changes.
The function that we pass to useEffect
is called the "effect function". This function will be executed when the component mounts and every time the dependencies of the hook change. Dependencies are passed as a second parameter in the form of an array. In this example, we pass [count]
as a dependency to useEffect
so that the effect function is called every time the value of count
changes.
Note that we can omit the array of dependencies if we want to execute the effect function only once, when the component mounts:
index.tsx332 chars17 lines
gistlibby LogSnag