Design Patterns · Middle · Question 36 of 75
How do you implement lazy initialization of a heavy object?
let client;
export function getClient() {
return (client ??= createHeavyClient());
}- ✓Correct answer: Create the object on first access and reuse it afterwards
- 2Create the object in a
setTimeoutso it doesn't block loading - 3Create a new object on every
getClientcall
Explanation
Lazy initialization saves startup time and resources if the object may not be needed. It's often combined with dynamic import() for heavy SDKs. Remember SSR: on the server such a module-level cache is shared by all requests.