hooks.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Add standard Hooks wrapper for React."""
  2. from reflex.utils.imports import ImportVar
  3. from reflex.vars import Var, VarData
  4. def _add_react_import(v: Var | None, tags: str | list):
  5. if v is None:
  6. return
  7. if isinstance(tags, str):
  8. tags = [tags]
  9. v._var_data = VarData( # type: ignore
  10. imports={"react": [ImportVar(tag=tag) for tag in tags]},
  11. )
  12. def const(name, value) -> Var | None:
  13. """Create a constant Var.
  14. Args:
  15. name: The name of the constant.
  16. value: The value of the constant.
  17. Returns:
  18. The constant Var.
  19. """
  20. return Var.create(f"const {name} = {value}")
  21. def useCallback(func, deps) -> Var | None:
  22. """Create a useCallback hook with a function and dependencies.
  23. Args:
  24. func: The function to wrap.
  25. deps: The dependencies of the function.
  26. Returns:
  27. The useCallback hook.
  28. """
  29. if deps:
  30. v = Var.create(f"useCallback({func}, {deps})")
  31. else:
  32. v = Var.create(f"useCallback({func})")
  33. _add_react_import(v, "useCallback")
  34. return v
  35. def useContext(context) -> Var | None:
  36. """Create a useContext hook with a context.
  37. Args:
  38. context: The context to use.
  39. Returns:
  40. The useContext hook.
  41. """
  42. v = Var.create(f"useContext({context})")
  43. _add_react_import(v, "useContext")
  44. return v
  45. def useRef(default) -> Var | None:
  46. """Create a useRef hook with a default value.
  47. Args:
  48. default: The default value of the ref.
  49. Returns:
  50. The useRef hook.
  51. """
  52. v = Var.create(f"useRef({default})")
  53. _add_react_import(v, "useRef")
  54. return v