Suggest an editImprove this articleRefine the answer for “What happens when a component mounts?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Mounting** is the process in which React creates an instance of the component, generates the Virtual DOM, compares it with the real DOM (if needed), inserts the elements into the browser DOM, and calls all the effects tied to mounting. **Key point:** `useEffect(() => {...}, [])` fires only once - on mount.Shown above the full answer for quick recall.Answer (EN)Image## What "mounting" is > **Mounting** is the process in which React: > > 1. Creates an instance of the component (or calls the function component), > 2. Generates the Virtual DOM, > 3. Compares it with the real DOM (if needed), > 4. Inserts the elements into the browser DOM, > 5. Calls all the effects tied to mounting (`useEffect`, `useLayoutEffect`). --- ## The mounting stages step by step ### 1. React calls the component If it is a **function component**, React simply calls it as a function: ```javascript function App() { console.log("Component called"); return <div>Hello</div>; } ``` If it is a **class component**, React creates an instance of the class (`new MyComponent()`), calls `constructor()` (if there is one), then `render()`. --- ### 2. React builds the Virtual DOM The component returns JSX -> React turns it into a **virtual tree of elements** (objects in memory). ```javascript return <div className="box">Hello</div>; ``` React creates an internal representation of this node: ```javascript { type: 'div', props: { className: 'box', children: 'Hello' } } ``` --- ### 3. React inserts the component into the real DOM Based on the Virtual DOM, React creates real DOM elements and adds them to the document. This is when you first "see" the component on screen. --- ### 4. React calls the **mount effects** Once the DOM is updated, React calls all hooks with an empty dependency array `[]`. #### Example: ```javascript useEffect(() => { console.log("Mounted"); }, []); ``` This code runs **once** - right after the first render and after being inserted into the DOM. This is the equivalent of `componentDidMount()` in class components. --- ### 5. React calls `useLayoutEffect` (if there is one) If you use `useLayoutEffect`, it fires **right after the DOM is created, but before painting**. This is useful for measuring elements or synchronizing positions. ```javascript useLayoutEffect(() => { const size = ref.current.getBoundingClientRect(); console.log("Size:", size); }, []); ``` --- ## What is usually done on mount | Task | Tool | |---|---| | Load data from an API | `useEffect(() => {...}, [])` | | Set up timers / intervals | `useEffect(() => { const id = setInterval(...); return () => clearInterval(id); }, [])` | | Add event listeners (scroll, resize) | `window.addEventListener()` inside `useEffect` | | Measure element sizes | `useLayoutEffect()` | | Initialize libraries (for example, Chart.js, Leaflet, Swiper) | `useEffect(() => { initLib(); }, [])` | --- ## Example ```javascript import { useEffect, useState } from "react"; function UserList() { const [users, setUsers] = useState([]); useEffect(() => { console.log("Component mounted - loading data..."); fetch("/api/users") .then(res => res.json()) .then(setUsers); }, []); // ← empty dependencies → runs once on mount return ( <ul> {users.map(u => <li key={u.id}>{u.name}</li>)} </ul> ); } ``` Here: - The component **renders for the first time**; - React inserts the `<ul>` into the DOM; - `useEffect` is called once -> it makes the request; - Once the data arrives, the component **updates**. --- ## For class components (the equivalent) ```javascript class UserList extends React.Component { state = { users: [] }; componentDidMount() { console.log("Component mounted"); fetch("/api/users") .then(res => res.json()) .then(users => this.setState({ users })); } render() { return <ul>{this.state.users.map(u => <li key={u.id}>{u.name}</li>)}</ul>; } } ``` Here the `componentDidMount()` method is used - it is called **once after the first render**. --- ## Important to remember | Trait | Explanation | |---|---| | `useEffect(() => {...}, [])` fires only once | On mount | | `useLayoutEffect()` fires earlier than `useEffect` | Before the screen is painted | | In React 18 Strict Mode, mount effects can be called twice in dev mode | This is a test of code stability | | If a component unmounts and mounts again (for example, conditional rendering), the effect runs again | Every mount = a new initialization | --- ## Summary | Stage | What React does | What the developer does | |---|---|---| | 1. Component call | Creates the Virtual DOM | Initializes the state (`useState`) | | 2. Render | Turns JSX into the Virtual DOM | Returns JSX | | 3. Insertion into the DOM | Adds elements to the page | Can work with the DOM (via `ref`) | | 4. Effects | Calls `useEffect` / `useLayoutEffect` | Loads data, adds listeners | | 5. UI is ready | The component now "lives" | Waits for an update or unmount | --- **Main idea:** > On **mount**, React creates and inserts the component into the DOM, > then calls the effects (`useEffect`, `useLayoutEffect`) to initialize data, listeners and logic. </content>For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.