blob: f5dcf0b95d993edacc7974d3dd3eca041b0b5e8a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package cursed
import "sync"
// UseState is a copy of the useState monad in React/Preact.
//
// This is a thread-safe stateful container that allows you to set
// and get a shared value.
//
// Consumers should take care to NOT mutate any values in the fetched
// variable.
func UseState[T any](initial T) (func() T, func(T)) {
var (
lock sync.Mutex
data T = initial
set = func(upda T) {
lock.Lock()
defer lock.Unlock()
data = upda
}
get = func() T {
lock.Lock()
defer lock.Unlock()
return data
}
)
return get, set
}
|