Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Add docs for use_callback, use_ref, hooks overview page #1012

Merged
merged 11 commits into from
Nov 19, 2024
86 changes: 86 additions & 0 deletions plugins/ui/docs/hooks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Hooks

_Hooks_ let you use state and other deephaven.ui features in your components. They are a way to reuse stateful logic between components. Hooks are functions that let you "hook into" state and lifecycle features from function components. You can either use the built-in hooks or combine them to build your own.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

## Example

```python
from deephaven import ui


@ui.component
def ui_counter():
count, set_count = ui.use_state(0)
return ui.button(f"Pressed {count} times", on_press=lambda: set_count(count + 1))


counter = ui_counter()
```

## UI recommendations

1. **Hooks must be used within components or other hooks**: Hooks require a rendering context, and therefore can only be used within component functions or other hooks. They cannot be used in regular Python functions or outside of components.
2. **All hooks start with `use_`**: For example, `use_state` is a hook that lets you add state to your components.
3. **Hooks must be called at the _top_ level**: Do not use hooks inside loops, conditions, or nested functions. This ensures that hooks are called in the same order each time a component renders. If you want to use one in a conditional or a loop, extract that logic to a new component and put it there.

## Built-in hooks

Below are all the built-in hooks that deephaven.ui provides.

### State hooks

_State_ lets a component remember some data between renders. State is a way to preserve data between renders and to trigger a re-render when the data changes. For example, a counter component might use state to keep track of the current count.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

To add state to a component, use the [`use_state`](use_state.md) hook.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

### Ref hooks

_Refs_ provide a way to hold a value that isn't used for re-rendering. Unlike with state, updating a ref does not re-render your component.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

- [`use_ref`](use_ref.md) returns a mutable ref object whose `.current` property is initialized to the passed argument.

### Effect hooks

_Effects_ let you perform side effects in your components. Data fetching, setting up a subscription, and manually synchronizing with an external system are all examples of side effects.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

- [`use_effect`](use_effect.md) lets you perform side effects in your components.

### Performance hooks

_Performance_ hooks let you optimize components for performance. They allow you to memoize expensive computations so that you can avoid re-running them on every render, or skip unnecessary re-rendering.

- [`use_memo`](use_memo.md) lets you memoize expensive computations.
- [`use_callback`](use_callback.md) lets you cache a function definition before passing to an effect or child component, preventing unnecessary rendering. It's like `use_memo` but specifically for functions.

### Data hooks

_Data_ hooks let you use data from within a Deephaven table in your component.

- [`use_table_data`](use_table_data.md) lets you use the full table contents.
- [`use_column_data`](use_column_data.md) lets you use the column data of one column.
mofojed marked this conversation as resolved.
Show resolved Hide resolved
- [`use_cell_data`](use_cell_data.md) lets you use the cell data of one cell.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have a ticket assigned to anyone to doc these?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created tickets #1014, #1015, #1016 and added to this PR

mofojed marked this conversation as resolved.
Show resolved Hide resolved

## Create custom hooks

You can create your own hooks to reuse stateful logic between components. A custom hook is a JavaScript function whose name starts with `use` and that may call other hooks. For example, let's say you want to create a custom hook that checks whether a table cell is odd. You can create a custom hook called `use_is_cell_odd`:

```python
from deephaven import time_table, ui


def use_is_cell_odd(table):
cell_value = ui.use_cell_data(table, 0)
return cell_value % 2 == 1


@ui.component
def ui_table_odd_cell(table):
is_odd = use_is_cell_odd(table)
return ui.view(f"Is the cell odd? {is_odd}")


_table = time_table("PT1s").update("x=i").view("x").tail(1)
table_odd_cell = ui_table_odd_cell(_table)
```

Notice at the end of our custom hook, we check if the cell value is odd and return the result. We then use this custom hook in our component to display whether the cell is odd.
57 changes: 57 additions & 0 deletions plugins/ui/docs/hooks/use_callback.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# use_callback

`use_callback` is a hook that memoizes a callback function, returning the same callback function on subsequent renders when the dependencies have not changed. This is useful when passing callbacks to functions or components that rely on reference equality to prevent unnecessary re-renders or effects from firing.

## Example

```python
from deephaven import ui
import time


@ui.component
def ui_server():
theme, set_theme = ui.use_state("red")

create_server = ui.use_callback(lambda: {"host": "localhost"}, [])

def connect():
server = create_server()
print(f"Connecting to {server}")
time.sleep(0.5)

ui.use_effect(connect, [create_server])

return ui.view(
ui.picker(
"red",
"orange",
"yellow",
label="Theme",
selected_key=theme,
on_change=set_theme,
),
padding="size-100",
background_color=theme,
)


my_server = ui_server()
```

In the example above, the `create_server` callback is memoized using `use_callback`. The `connect` function is then passed to [`use_effect`](./use_effect.md) with `create_server` as a dependency. This ensures that the effect will not be triggered on every re-render because the `create_server` callback is memoized.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

`use_callback` is similar to [`use_memo`](./use_memo.md), but for functions instead of values. Use `use_callback` when you need to memoize a callback function that relies on reference equality to prevent unnecessary re-renders.

## Recommendations

Recommendations for memoizing callback functions:

1. **Use memoization when callbacks passed into expensive effects**: If the callback is being passed into an expensive `use_effect` or `use_memo` call, `use_callback` so that it maintains referential equality.
mofojed marked this conversation as resolved.
Show resolved Hide resolved
2. **Use dependencies**: Pass in only the dependencies that the memoized callback relies on. If any of the dependencies change, the memoized callback will be re-computed.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

## API Reference

```{eval-rst}
.. dhautofunction:: deephaven.ui.use_callback
```
31 changes: 31 additions & 0 deletions plugins/ui/docs/hooks/use_cell_data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# use_cell_data

`use_cell_data` lets you use the cell data of the first cell in a table. This is useful when you want to listen to an updating table and use the data in your component.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

## Example

```python
from deephaven import time_table, ui


@ui.component
def ui_table_first_cell(table):
cell_value = ui.use_cell_data(table)
return ui.heading(f"The first cell value is {cell_value}")


table_first_cell = ui_table_first_cell(time_table("PT1s").tail(1))
```

In the above example, `ui_table_first_cell` is a component that listens to the last row of a table and displays the value of the first cell. The `cell_value` variable is updated every time the table updates.

## Recommendations

1. **Use `use_cell_data` for listening to table updates**: If you need to listen to a table for one cell of data, use `use_cell_data`.
2. **Use table operations to filter to one cell**: If your table has multiple rows and columns, use table operations such as `.where` and `.select` to filter to the cell you want to listen to. `use_cell_data` always uses the top-left cell of the table.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

## API Reference

```{eval-rst}
.. dhautofunction:: deephaven.ui.use_cell_data
```
31 changes: 31 additions & 0 deletions plugins/ui/docs/hooks/use_column_data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# use_column_data

`use_column_data` lets you use the column data of a table. This is useful when you want to listen to an updating table and use the data in your component.
mofojed marked this conversation as resolved.
Show resolved Hide resolved

## Example

```python
from deephaven import time_table, ui


@ui.component
def ui_table_column(table):
column_data = ui.use_column_data(table)
return ui.heading(f"The column data is {column_data}")


table_column = ui_table_column(time_table("PT1s").tail(5))
```

In the above example, `ui_table_column` is a component that listens to the last 5 rows of a table and displays the values of the first column. The `column_data` variable is updated every time the table updates.

## Recommendations

1. **Use `use_column_data` for listening to table updates**: If you need to listen to a table for one column of data, use `use_column_data`.
2. **Use table operations to filter to one column**: If your table has multiple rows and columns, use table operations such as `.where` and `.select` to filter to the column you want to listen to. `use_column_data` always uses the first column of the table.

## API Reference

```{eval-rst}
.. dhautofunction:: deephaven.ui.use_column_data
```
80 changes: 80 additions & 0 deletions plugins/ui/docs/hooks/use_ref.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# use_ref

`use_ref` returns a mutable ref object whose `.current` property is initialized to the passed argument. The returned object will persist for the full lifetime of the component. Updating the `.current` property will not trigger a re-render.

## Example

```python
from deephaven import ui


@ui.component
def ui_ref_counter():
ref = ui.use_ref(0)

def handle_press():
ref.current += 1
print(f"You clicked {ref.current} times!")

return ui.button("Click me!", on_press=handle_press)


ref_counter = ui_ref_counter()
```

Note that we're only using the `ref.current` value within the `handle_press` method. This is because updating the ref does not trigger a re-render, so the component will not reflect the updated value. The value will be printed out each time you press the button. If you need to update the component based on the ref value, consider using `use_state` instead.

## Recommendations

1. **Use `use_ref` for mutable values**: If you need to store a mutable value that doesn't affect the component's rendering, use `use_ref`.
2. **Use `use_state` for values that affect rendering**: If you need to store a value that will affect the component's rendering, use `use_state` instead of `use_ref`.

## Stopwatch example

Here's an example of a stopwatch using `use_ref`. Press the Start button to start the stopwatch, and the Stop button to stop it. The elapsed time will be displayed in the text field:
mofojed marked this conversation as resolved.
Show resolved Hide resolved

```python
from deephaven import ui
import datetime
from threading import Timer


class RepeatTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)


@ui.component
def ui_stopwatch():
start_time, set_start_time = ui.use_state(datetime.datetime.now())
now, set_now = ui.use_state(start_time)
timer_ref = ui.use_ref(None)

def stop():
if timer_ref.current is not None:
timer_ref.current.cancel()

def start():
stop()
new_start_time = datetime.datetime.now()
set_start_time(new_start_time)
set_now(new_start_time)
timer_ref.current = RepeatTimer(0.01, lambda: set_now(datetime.datetime.now()))
timer_ref.current.start()

return ui.view(
ui.heading(f"Elapsed time: {now - start_time}"),
ui.button("Start", on_press=start),
ui.button("Stop", on_press=stop),
)


stopwatch = ui_stopwatch()
```

## API Reference

```{eval-rst}
.. dhautofunction:: deephaven.ui.use_ref
```
31 changes: 31 additions & 0 deletions plugins/ui/docs/hooks/use_table_data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# use_table_data

`use_table_data` lets you use the data of a table. This is useful when you want to listen to an updating table and use the data in your component.

## Example

```python
from deephaven import time_table, ui


@ui.component
def ui_table_data(table):
table_data = ui.use_table_data(table)
return ui.heading(f"The table data is {table_data}")


table_data = ui_table_data(time_table("PT1s").update("x=i").tail(5))
```

In the above example, `ui_table_data` is a component that listens to the last 5 rows of a table and displays the data. The `table_data` variable is updated every time the table updates.

## Recommendations

1. **Use `use_table_data` for listening to table updates**: If you need to listen to a table for all the data, use `use_table_data`.
2. **Use table operations to filter to the data you want**: If your table has multiple rows and columns, use table operations such as `.where` and `.select` to filter to the data you want to listen to.

## API Reference

```{eval-rst}
.. dhautofunction:: deephaven.ui.use_table_data
```
24 changes: 24 additions & 0 deletions plugins/ui/docs/sidebar.json
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,26 @@
{
"label": "Hooks",
"items": [
{
"label": "Overview",
"path": "hooks/README.md"
mofojed marked this conversation as resolved.
Show resolved Hide resolved
},
{
"label": "use_boolean",
"path": "hooks/use_boolean.md"
},
{
"label": "use_callback",
"path": "hooks/use_callback.md"
},
{
"label": "use_cell_data",
"path": "hooks/use_cell_data.md"
},
{
"label": "use_column_data",
"path": "hooks/use_column_data.md"
},
{
"label": "use_effect",
"path": "hooks/use_effect.md"
Expand All @@ -158,9 +174,17 @@
"label": "use_memo",
"path": "hooks/use_memo.md"
},
{
"label": "use_ref",
"path": "hooks/use_ref.md"
},
{
"label": "use_state",
"path": "hooks/use_state.md"
},
{
"label": "use_table_data",
"path": "hooks/use_table_data.md"
}
]
}
Expand Down
Loading