hooks.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """Add standard Hooks wrapper for React."""
  2. from __future__ import annotations
  3. from reflex.utils.imports import ImportVar
  4. from reflex.vars import VarData
  5. from reflex.vars.base import Var
  6. def _compose_react_imports(tags: list[str]) -> dict[str, list[ImportVar]]:
  7. return {"react": [ImportVar(tag=tag) for tag in tags]}
  8. def const(name: str | list[str], value: str | Var) -> Var:
  9. """Create a constant Var.
  10. Args:
  11. name: The name of the constant.
  12. value: The value of the constant.
  13. Returns:
  14. The constant Var.
  15. """
  16. if isinstance(name, list):
  17. return Var(_js_expr=f"const [{', '.join(name)}] = {value}")
  18. return Var(_js_expr=f"const {name} = {value}")
  19. def useCallback(func: str, deps: list) -> Var: # noqa: N802
  20. """Create a useCallback hook with a function and dependencies.
  21. Args:
  22. func: The function to wrap.
  23. deps: The dependencies of the function.
  24. Returns:
  25. The useCallback hook.
  26. """
  27. return Var(
  28. _js_expr=f"useCallback({func}, {deps})" if deps else f"useCallback({func})",
  29. _var_data=VarData(imports=_compose_react_imports(["useCallback"])),
  30. )
  31. def useContext(context: str) -> Var: # noqa: N802
  32. """Create a useContext hook with a context.
  33. Args:
  34. context: The context to use.
  35. Returns:
  36. The useContext hook.
  37. """
  38. return Var(
  39. _js_expr=f"useContext({context})",
  40. _var_data=VarData(imports=_compose_react_imports(["useContext"])),
  41. )
  42. def useRef(default: str) -> Var: # noqa: N802
  43. """Create a useRef hook with a default value.
  44. Args:
  45. default: The default value of the ref.
  46. Returns:
  47. The useRef hook.
  48. """
  49. return Var(
  50. _js_expr=f"useRef({default})",
  51. _var_data=VarData(imports=_compose_react_imports(["useRef"])),
  52. )
  53. def useState(var_name: str, default: str | None = None) -> Var: # noqa: N802
  54. """Create a useState hook with a variable name and setter name.
  55. Args:
  56. var_name: The name of the variable.
  57. default: The default value of the variable.
  58. Returns:
  59. A useState hook.
  60. """
  61. return const(
  62. [var_name, f"set{var_name.capitalize()}"],
  63. Var(
  64. _js_expr=f"useState({default})",
  65. _var_data=VarData(imports=_compose_react_imports(["useState"])),
  66. ),
  67. )