use_reactive
Creates a reactive variable with the a local component scope.
def use_reactive(
value: Union[T, solara.Reactive[T]],
on_change: Optional[Callable[[T], None]] = None,
) -> solara.Reactive[T]:
...
It is a useful alternative to use_state
when you want to use a
reactive variable for the component state.
See also our documentation on state management.
If the variable passed is a reactive variable, it will be returned instead and no
new reactive variable will be created. This is useful for implementing component
that accept either a reactive variable or a normal value along with an optional on_change
callback.
Note that that on each call, if the value changes, the reactive variable will be updated. For objects that do no implement equality comparison, the will lead to an infinite loop.
In that case, combine the use_reactive
with use_memo
to never trigger an update from
the render function.
@solara.component
def Page():
data = solara.use_reactive(solara.use_memo(lambda: MyDataObject()))
...
Arguments:
value (Union[T, solara.Reactive[T]]): The value of the reactive variable. If a reactive variable is provided, it will be used directly. Otherwise, a new reactive variable will be created with the provided initial value. If the argument passed changes the reactive variable will be updated.
on_change (Optional[Callable[[T], None]]): An optional callback function that will be called when the reactive variable's value changes.
Returns: solara.Reactive[T]: A reactive variable with the specified initial value or the provided reactive variable.
Examples
Replacement for use_state
import solara
@solara.component
def ReusableComponent():
color = solara.use_reactive("red") # another possibility
solara.Select(label="Color",values=["red", "green", "blue", "orange"],
value=color)
solara.Markdown("### Solara is awesome", style={"color": color.value})
@solara.component
def Page():
# this component is used twice, but each instance has its own state
ReusableComponent()
ReusableComponent()
Solara is awesome
Solara is awesome
Flexible arguments
The MyComponent
component can be passed a reactive variable or a normal
Python variable and a on_value
callback.
import solara
from typing import Union, Optional, Callable
@solara.component
def MyComponent(value: Union[T, solara.Reactive[T]],
on_value: Optional[Callable[[T], None]] = None,
):
reactive_value = solara.use_reactive(value, on_value)
# Use the `reactive_value` in the component