effect
The effect()
function allows you to run side effects in response to changes in state variables. This is useful for DOM updates, event subscriptions, or any logic that should re-run when specific dependencies change.
Use Cases
Use effect()
to respond to changes in props, computed values, or manually declared dependencies. It works similarly to React's useEffect
but is scoped and dependency-aware inside the PPHP lifecycle.
Syntax
effect(() => { // reactive code here }, ['myState', 'otherState']);
fn
: The function to run when dependencies change.deps
(optional): An array of strings (state keys) or functions (accessors) that serve as dependencies. If omitted, the effect will run after every flush cycle.
Behavior
- If no
deps
are provided, the effect is treated as global and runs after every reactive update. - If
deps
is an empty array[]
, the effect runs only once and is never registered again. - Each dependency is scoped automatically based on its section and tracking context.
- The effect is registered for future re-evaluation when its tracked keys are mutated.
- The return value is a cleanup function that can be called to remove the effect manually.
Run Always Example
<script>
pphp.effect(() => {
console.log('This runs every time a state changes');
});
</script>
This example will log a message every time a state changes. It is useful for debugging or tracking changes in your application.
Run on State Change Example
<button onclick="() => count++">Increment</button>
<p>{{ message }}</p>
<script>
pphp.state('count', 0);
pphp.state('message', '');
pphp.effect(() => {
if (count > 5) {
message = 'Count is high!';
} else {
message = 'Keep counting...';
}
}, ['count']);
</script>
In this example, the effect will run every time count
changes and update the message
accordingly. Since message
is also reactive, any DOM bindings will reflect the change.
Run Once Example
<script>
pphp.effect(() => {
console.log('This runs only once');
}, []);
</script>
Passing an empty array makes the effect run once when the section is initialized and skips future executions.