state
The state()
function defines a reactive state variable and returns a getter/setter pair. This enables you to store, read, and update local data with automatic DOM reactivity when values change.
Use Cases
Use state()
when you want to bind dynamic data in your templates or react to changes with effect()
. It’s perfect for form fields, counters, toggles, and local variables scoped to a section or component.
Syntax
const [count, setCount] = pphp.state('count', 0); // or initialize without destructuring pphp.state('count', 0);
key
: A string that uniquely identifies the state variable. Must not collide with reserved native objects.initial
: The initial value of the state (can be any type: string, number, boolean, object, etc).- Returns: A tuple
[getter, setter]
where:getter()
returns the current value and is also callable directly in bindings.setter(value)
updates the value (or accepts a callback for functional updates).
Behavior
- Scoped automatically to the current section if inside a component.
- If the state key already exists, it is preserved; otherwise initialized with the given value.
- State keys are reactive and trigger updates to bound DOM elements or effects.
- Getter can be used like a normal function, or as a value in expressions.
- Functional updates supported:
setValue(prev => prev + 1)
. - Throws an error if using a reserved name like
Object
,Array
, etc.
Example Usage
<button onclick="() => { setCount(prev => prev + 1); setLabel('Clicked!') }">
Increment
</button>
<p>Count is: {{ count }}</p>
<p>Label: {{ label }}</p><script>
const [count, setCount] = pphp.state('count', 0);
const [label, setLabel] = pphp.state('label', 'Click the button');
</script>
In this example, both count
and label
are reactive. When the button is clicked, the values are updated using the setter, and all bound elements update automatically.
Run-Only Getter (Read-Only)
You can also use the getter without destructuring if you don’t need the setter:
<body class="{{ theme }}"></body>
<script>
pphp.state('theme', 'dark');
</script>