Hooks
Hooks are classes with the ability to use states and manage side effects. They are a fundamental concept in Reactter and are used to encapsulate logic that can be reused across the application.
API
Reactter provider some hooks to manage the state and side effects of the application, which are:
How it works
Hooks in Reactter are classes that extend RtHook
and follow a special naming convention with the Use
prefix. The RtHook
class is responsible for binding the hook to other hooks and states, and managing the lifecycle of the hook.
Hooks in Reactter are essentially stateful entities because RtHook
inherits from RtState
this inheritance allows hooks to manage both state and lifecycle methods efficiently.
To manage these aspects, Hooks provide the following:
-
Methods inherited from
RtState
(Learn more here):-
update
: A method to notify changes after run a set of instructions. -
refresh
: A method to force to notify changes. - *
bind
: A method to bind an instance to it. - *
unbind
: A method to unbind an instance to it. - *
dispose
: A method to remove all listeners and free resources.
-
Custom hook
Reactter provides a way to create Custom Hooks to encapsulate logic that can be reused across the application.
There are several advantages to using Custom Hooks:
- Reusability: to use the same hook again and again, without the need to write it twice.
- Clean Code: extracting part of code into a hook will provide a cleaner codebase.
- Maintainability: easier to maintain. if you need to change the logic of the hook, you only need to change it once.
Creating a custom hook
To create a Custom hook, you need to create a class that extends RtHook
and follow the naming convention with the Use
prefix.
Here’s an example of a Custom Hook that manages the state of a text input:
As shown in the example above, we can utilize other hooks such as UseEffect
to monitor changes in the text input’s controller and ensure it is disposed when the hook is destroyed.
The update
method is used to set the internal _value
to the current text in the controller, which keeps the state synchronized with the input.
This methods is a part of the RtHook
class that allows you to update the state of the hook.
Using a custom hook
You can then call that Custom Hook from anywhere in the code and get access to its shared logic:
In the example above, the form captures first and last name inputs, combines them into a full name, and displays the result.
MyController
uses UseTextInput
hook for capturing the first and last name.
The fullName
state is defined using UseCompute
to compute the full name based on the values of firstNameInput
and lastNameInput
. This ensures the full name is automatically updated whenever either input changes.