-
Notifications
You must be signed in to change notification settings - Fork 16
/
hooks.go
48 lines (42 loc) · 1 KB
/
hooks.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package spot
func UseState[T any](ctx *RenderContext, initial T) (T, func(next T)) {
ctx.mutex.Lock()
defer ctx.mutex.Unlock()
n := ctx.count
ctx.count++
setterFn := func(next T) {
ctx.mutex.Lock()
ctx.values[n] = next
ctx.mutex.Unlock()
ctx.TriggerUpdate()
}
if v, ok := ctx.values[n]; ok {
// fmt.Printf("Using state %d for value: %v (initially %v)\n", n, v.(T), initial)
return v.(T), setterFn
}
// fmt.Printf("Setting up state %d with initial value %v\n", n, initial)
ctx.values[n] = initial
return initial, setterFn
}
func UseEffect(ctx *RenderContext, fn func(), deps []any) {
vals, setVals := UseState[[]any](ctx, nil)
if deps == nil && vals != nil || (vals != nil && len(deps) != len(vals)) {
panic("UseEffect: Length of dependencies changed")
}
changed := false
if vals == nil {
// first call: Always run the effect
changed = true
} else {
for i, dep := range deps {
if dep != vals[i] {
changed = true
break
}
}
}
if changed {
setVals(deps)
fn()
}
}