0 day streak
javascript / beginner
Snippet

The useEffect Hook (Mounting)

The useEffect hook allows you to perform side effects in functional components. When passed an empty dependency array ([]), it runs exactly once after the initial render, similar to 'componentDidMount' in class components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
console.log('Component mounted!');
}, []);
return <div>Hello World</div>;
}
react
Breakdown
1
useEffect(() => { ... }, []);
Defines the effect function and an empty dependency array to ensure it only runs once.
2
console.log('Component mounted!');
The logic inside this block executes after the component is added to the DOM.