top of page
Logo der Online Agentur mdwp


`useEffect` is a built-in hook in React that allows you to perform side effects in your function components. Side effects are basically anything that interacts with the outside of your components, may it be data fetching, subscribing to some sort of events, manually changing the DOM, etc.

`useEffect` is used to handle the side effects that don't directly involve rendering cycle changes. It runs asynchronously and after a render is completed. It has a similar purpose to `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` class lifecycle methods combined in class components.

Here is a basic example of how you might use `useEffect`:

import React, { useState, useEffect } from 'react';

function Example() {
const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;

// Optionally, you can return a cleanup function
return () => {
// Equivalent to componentWillUnmount
document.title = `React App`;
}, [count]); // Only re-run the effect if count changes

return (
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me

export default Example;

In this code, the `useEffect` function is being called with two arguments, first is a callback function that will contain our side effects code, second is an array of dependencies. When we pass an empty array `[]`, it means the `useEffect` will run only once after the initial render (similar to `componentDidMount` in class components). Here, `[count]` implies that the side effect will run every time the `count` value changes.

bottom of page