This is the latest docs version
Quick Links
  • -Overview
  • -Language Features
  • -JS Interop
  • -Build System
Documentation
Language Manual
Reference for all language features
ReScript & React
First class bindings for ReactJS
GenType
Seamless TypeScript integration
Reanalyze
Dead Code & Termination analysis
Exploration
Packages
Explore third party libraries and bindings
Syntax Lookup
Discover all syntax constructs
APIPlaygroundBlogCommunity
  • Playground
  • Blog
  • Twitter
  • GitHub
  • Forum
Language Manual
Overview
  • Introduction
  • Installation
  • Migrate to v11
  • Editor Plugins
  • Try
Language Features
  • Overview
  • Let Binding
  • Type
  • Primitive Types
  • Tuple
  • Record
  • Object
  • Variant
  • Polymorphic Variant
  • Null, Undefined and Option
  • Array & List
  • Function
  • If-Else & Loops
  • Pipe
  • Pattern Matching / Destructuring
  • Mutation
  • JSX
  • Exception
  • Lazy Value
    • Execute The Lazy Computation
    • Exception Handling
  • Promises
  • Async / Await
  • Tagged templates
  • Module
  • Import & Export
  • Attribute (Decorator)
  • Reserved Keywords
  • Equality and Comparison
Advanced Features
  • Extensible Variant
  • Scoped Polymorphic Types
JavaScript Interop
  • Interop Cheatsheet
  • Embed Raw JavaScript
  • Shared Data Types
  • External (Bind to Any JS Library)
  • Bind to JS Object
  • Bind to JS Function
  • Import from / Export to JS
  • Bind to Global JS Values
  • JSON
  • Inlining Constants
  • Use Illegal Identifier Names
  • Generate Converters & Helpers
  • Browser Support & Polyfills
  • Libraries & Publishing
  • TypeScript
Build System
  • Overview
  • Configuration
  • Configuration Schema
  • External Stdlib
  • Pinned Dependencies
  • Interop with JS Build Systems
  • Performance
  • Warning Numbers
Guides
  • Converting from JS
Extra
  • Newcomer Examples
  • Project Structure
  • FAQ
Docs / Language Manual / Lazy Value
Edit

Lazy Value

If you have some expensive computations you'd like to defer and cache subsequently, you can wrap it with lazy:

ReScriptJS Output
@module("node:fs")
external readdirSync: string => array<string> = "readdirSync"

// Read the directory, only once
let expensiveFilesRead = lazy({
  Console.log("Reading dir")
  readdirSync("./pages")
})

Check the JS Output tab: that expensiveFilesRead's code isn't executed yet, even though you declared it! You can carry it around without fearing that it'll run the directory read.

Note: a lazy value is not a shared data type. Don't rely on its runtime representation in your JavaScript code.

Execute The Lazy Computation

To actually run the lazy value's computation, use Lazy.force from the globally available Lazy module:

ReScriptJS Output
// First call. The computation happens
Console.log(Lazy.force(expensiveFilesRead)) // logs "Reading dir" and the directory content

// Second call. Will just return the already calculated result
Console.log(Lazy.force(expensiveFilesRead)) // logs the directory content

The first time Lazy.force is called, the expensive computation happens and the result is cached. The second time, the cached value is directly used.

You can't re-trigger the computation after the first force call. Make sure you only use a lazy value with computations whose results don't change (e.g. an expensive server request whose response is always the same).

Instead of using Lazy.force, you can also use pattern matching to trigger the computation:

ReScriptJS Output
switch expensiveFilesRead {
| lazy(result) => Console.log(result)
}

Since pattern matching also works on a let binding, you can also do:

ReScriptJS Output
let lazy(result) = expensiveFilesRead
Console.log(result)

Exception Handling

For completeness' sake, our files read example might raise an exception because of readdirSync. Here's how you'd handle it:

ReScriptJS Output
let result = try {
  Lazy.force(expensiveFilesRead)
} catch {
| Not_found => [] // empty array of files
}

Though you should probably handle the exception inside the lazy computation itself.

ExceptionPromises

© 2024 The ReScript Project

Software and assets distribution powered by KeyCDN.

About
  • Community
  • ReScript Association
Find us on