Lazy Function
Definition
A Lazy Function can also be called as Lazy evaluation.
In programming language theory, lazy evaluation, or call-by-need,[1] is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which avoids repeated evaluations (by the use of sharing).
Example
By making the copyToClipboard
function lazy, the if (navigator.clipboard)
condition only needs to be run once per runtime.
1 | function copyToClipboard(text) { |
1 | function copyToClipboard(text) { |
1 | function copyToClipboard(text) { |
In Vue/React?
In Vue and React, there are some built-in features or APIs that implement lazy evaluation, mainly for performance optimization and avoiding unnecessary calculations.
React
Feature / API | Lazy or not | Description |
---|---|---|
useMemo(fn, deps) | ✅ Yes | fn is called only when dependencies change, otherwise the last cached value is returned. |
useCallback(fn, deps) | ✅ Yes | Similar to useMemo , used to cache function references to avoid re-rendering of child components. |
React.lazy(() => import()) | ✅ Yes | Dynamically import components and load the corresponding module until rendering is needed. |
Suspense + lazy | ✅ Yes | Used with React.lazy to delay loading resources until they are needed. |
useDeferredValue | ⚠️ Partially lazy | It is “delayed update” rather than lazy evaluation, used for low-priority rendering. |
useTransition | ⚠️ Delayed rendering | Used to delay some updates, it is “delayed scheduling” rather than true lazy calculation. |
Vue
Features / API | Lazy or not | Description |
---|---|---|
computed | ✅ Yes | Recalculate only when dependencies change, otherwise return cached values. |
watchEffect | ✅ Yes | Although dependencies are automatically collected, the execution body is run after the dependencies are first established. |
defineAsyncComponent | ✅ Yes | Similar to React.lazy , components are only loaded when they are actually used. |
v-once | ✅ Yes | After rendering once, it will not be updated again, similar to static cache. |
suspense | ✅ Yes | Used to handle asynchronous component loading, used with async component. |
Summary
Lazy evaluation usually appears in the following scenarios:
Performance optimization: Avoid repeated execution of expensive calculations (such as
computed
,useMemo
).Lazy loading: Reduce the size of the first screen (such as
React.lazy
,defineAsyncComponent
).Side effect control: Only trigger side effects when dependencies change (such as
watch
,useEffect
).