The initial render is the 1st time that the component tree is rendered to the DOM. It happens when the application first loads, or when the root component is first rendered. (also known as "mounting" the components)
Re-renders, on the other hand, happen when the components's state or props change, and the component needs to be updated in the DOM to reflect these changes.
React uses a virtual DOM to optimize the process of updating the actual DOM, so that only the necessary changes are made.
- changing the component's state or props.
- Parent element re-render => Child also re-render, even though its state or props haven't changed. (need optimization)
- starts with prefix use (both react built-in and custom hooks)
- component must be uppercase (i don't understand this ?)
- invoke inside function/component body.
- hooks can't be called conditionally (no
if (condition) useState(); else ...)
) - set functions don't update state immediately.
In React, "batching" refers to the process of grouping multiple state updates into a single update. E.g.
// original
const [name, setName] = useState('')
const [age, setAge] = useState(-1)
// alternatives
const [person, setPerson] = useState({name: '', age: -1})
This can be useful in certain cases because it allows React to optimize the rendering of your components by minimizing the number of DOM updates that it has to perform. Like example above, 2 DOM updates => 1 DOM updates.
By default, React uses a technique called "auto-batching" to group state updates that occur within the same event loop into a single update.
=> This means that if you call the state update function multiple times in a short period of time, React will only perform a single re-render for all of the updates.
React 18 ensures that state updates invoked from any location will be batched by default. This will batch state updates, including native event handlers, async operations, timeouts and intervals.
setValue(value + 1)
vs setValue(prevValue => prevValue + 1)
are VERY DIFFERENT!
- The former doesn't sync value, it postponed to AFTER the components re-render. Calling method multiple time before re-rendering will capture only old value of
value
. - The latter sync immediately, multiple calling method results in multiple
prevValue
update, regardless of re-rendering process.
Allows you to perform side effects in function components. 'side effects' are any work outside of React component. Example? subscriptions, data fetching, directly updating the DOM, event listeners, ...