pp-init-state
The
pp-init-state
directive is used to initialize reactive state variables directly in your DOM elements.
It provides a declarative way to set up initial values, especially useful when creating
standalone components without needing an explicit
<script>
block.
Use Cases
- Quickly set initial values for state variables in a component.
- Make small, reusable widgets that don’t need separate JavaScript logic.
- Use in static templates or CMS systems where embedding scripts might be cumbersome.
Syntax
-
Use the attribute
pp-init-state
with a JSON object to define your initial state. - Each key in the JSON becomes a state variable scoped to the current component or hierarchy.
Behavior
-
State initialized via
pp-init-state
is tracked reactively just like state declared usingpphp.state()
in script blocks. -
⚠️ Precedence: If the same variable is also initialized using
pphp.state()
, the value frompp-init-state
will take precedence and override it. - It’s ideal for initialization only — complex logic or computed values should still go inside a script tag where you have full control.
-
The
pp-init-state
attribute is removed from the DOM after initialization to keep your markup clean.
Example Usage
Below is a simple example where a counter is initialized to 5
using
pp-init-state
and then updated with buttons.
<div pp-init-state='{ "count": 5 }'>
<p>Current count: {{ count }}</p>
<button onclick="count++">Increment</button>
<button onclick="count--">Decrement</button>
</div>
In this example, the count
variable starts at 5
and is immediately reactive.
Clicking the buttons changes its value, which updates the displayed count automatically.
⚠️ For more advanced initialization, computed values, or effects,
prefer using a dedicated <script>
block with
pphp.state()
and pphp.effect()
for maximum flexibility and maintainability.
Remember: pp-init-state
values will override any identical
variables set via pphp.state()
.