Skip to content

Commit 9c133cb

Browse files
committed
feat: document ref for self-referencing
1 parent 667aaea commit 9c133cb

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

pages/docs/manual/v11.0.0/mutation.mdx

+44
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,47 @@ Note that the previous binding `five` stays `5`, since it got the underlying ite
7373
## Tip & Tricks
7474

7575
Before reaching for `ref`, know that you can achieve lightweight, local "mutations" through [overriding let bindings](let-binding.md#binding-shadowing).
76+
77+
### Self-Referencing Assignments
78+
79+
There are scenarios where using a mutable `ref` binding becomes necessary, particularly when dealing with self-referencing. This is common when working with functions that return a value and accept a callback that uses that return value. In such cases, you need to initialize a mutable `ref` binding and then assign to it. Here's an example:
80+
81+
<CodeTab labels={["ReScript", "JS Output"]}>
82+
83+
```res example
84+
// hypothetic "showDialog" function shows the given `~content: JSX.element`
85+
// in the dialog. It returns a cleanup function that closes/removes the dialog.
86+
@val external showDialog: (~content: Jsx.element) => unit => unit = "showDialog"
87+
88+
// We want render a "Close" button in the `~content` that will call the
89+
// returned cleanup function when clicked. This requires a mutable binding.
90+
// First initialize it with a dummy function that has the same signature as
91+
// our cleanup function.
92+
let cleanupDialog = ref(() => ())
93+
94+
// assign to the ref and self-refer to the value in the event handler
95+
cleanupDialog :=
96+
showDialog(
97+
~content=<div>
98+
<button onClick={_ => cleanupDialog.contents()}>
99+
{React.string("Close")}
100+
</button>
101+
</div>,
102+
)
103+
```
104+
```js
105+
var cleanupDialog = {
106+
contents: (function () {})
107+
};
108+
109+
cleanupDialog.contents = showDialog(JsxRuntime.jsx("div", {
110+
children: JsxRuntime.jsx("button", {
111+
children: "Close",
112+
onClick: (function (param) {
113+
cleanupDialog.contents();
114+
})
115+
})
116+
}));
117+
```
118+
119+
</CodeTab>

0 commit comments

Comments
 (0)