Skip to content

Commit

Permalink
fix: fix use_callback hook (#468)
Browse files Browse the repository at this point in the history
Fixes #403

I went with Matt's implementation as that seems to mirror React's
implementation and it seems to work as intended.
These examples now work
```
import deephaven.ui as ui
from deephaven.ui import use_state

@ui.component
def counter():
    count, set_count = use_state(0)
    on_press = ui.use_callback(lambda: set_count(lambda c: c + 1), [])
    return ui.action_button(
        f"You pressed me {count} times", on_press=on_press
    )

c = counter()
```
```

import deephaven.ui as ui
from deephaven.ui import use_state

@ui.component
def counter():
    count, set_count = use_state(0)
    on_press = ui.use_callback(lambda _: set_count(count + 1), [count])

    ui.use_effect(lambda: print('Effect'), [on_press])

    return ui.action_button(
        f"You pressed me {count} times", on_press=on_press
    )

c = counter()
```
  • Loading branch information
jnumainville authored May 23, 2024
1 parent ca65b69 commit f267572
Showing 1 changed file with 6 additions and 16 deletions.
22 changes: 6 additions & 16 deletions plugins/ui/src/deephaven/ui/hooks/use_callback.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,20 @@
from __future__ import annotations

from typing import Callable, Any, Sequence
from typing import Callable

from .use_ref import use_ref, Ref
from .use_memo import use_memo
from ..types import Dependencies


def use_callback(func: Callable, dependencies: Dependencies) -> Callable:
"""
Create a stable handle for a callback function. The callback will only be recreated if the dependencies change.
Memoize a callback function. The callback will only be recreated if the dependencies change.
Args:
func: The function to create a stable handle to.
func: The function to create a memoized callback for.
dependencies: The dependencies to check for changes.
Returns:
The stable handle to the callback function.
The memoized callback function.
"""
deps_ref: Ref[set[Any] | Sequence[Any] | None] = use_ref(None)
callback_ref = use_ref(lambda: None)
stable_callback_ref = use_ref(
lambda *args, **kwargs: callback_ref.current(*args, **kwargs)
)

if deps_ref.current != dependencies:
callback_ref.current = func
deps_ref.current = dependencies

return stable_callback_ref.current
return use_memo(lambda: func, dependencies)

0 comments on commit f267572

Please sign in to comment.