Skip to content

Commit

Permalink
modified: react/one-time-initialisation-in-component.md
Browse files Browse the repository at this point in the history
  • Loading branch information
byt3h3ad committed May 21, 2024
1 parent 5eb82d8 commit 16fd268
Showing 1 changed file with 2 additions and 19 deletions.
21 changes: 2 additions & 19 deletions react/one-time-initialisation-in-component.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,8 @@ const Component = () => {
> )
> ```
The same functionality can be achieve the same with useRef -
```js
const Component = () => {
// ✅ also works, but meh
const resource = React.useRef(null)
if (!resource.current) {
resource.current = new Resource()
}
return (
<ResourceProvider resource={resource.current}>
<App />
</ResourceProvider>
)
}
```
However, this looks rather convoluted, and TypeScript will also not like it, because `resource.current` can technically be `null`.

[source](https://x.com/housecor/status/1792526262751117371)
[further reading](https://tkdodo.eu/blog/use-state-for-one-time-initializations)
[why not to use useRef](https://x.com/TkDodo/status/1792549972539273278)

0 comments on commit 16fd268

Please sign in to comment.