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());
}

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.

Further reading

Problem with a question

Design Patterns · Middle · question 36

Test yourself

Take the Design Patterns · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz