watch
Method to watch for state changes and execute side effects.
Description
The watch
method allows you to subscribe to state changes and execute side effects when the state updates. Unlike use
, this doesn't trigger component re-renders but instead runs the provided callback function whenever the state changes.
Input/Output
Input | Type | Description |
---|---|---|
callback | (value: T) => void | Function to execute when state changes |
deps | DependencyList (optional) | Dependency array for when to re-subscribe |
Output | Type | Description |
---|---|---|
Returns | void | No return value |
Example
typescript
import { signify } from "react-signify";
import { useEffect } from "react";
const sCounter = signify(0);
const sUser = signify({ name: "John", age: 25 });
function MyComponent() {
// Watch counter changes
sCounter.watch((newValue) => {
console.log("Counter changed to:", newValue);
if (newValue > 10) {
alert("Counter exceeded 10!");
}
});
// Watch user changes with dependencies
sUser.watch((newUser) => {
localStorage.setItem("user", JSON.stringify(newUser));
}, []);
return (
<div>
<button onClick={() => sCounter.set(sCounter.value + 1)}>
Increment
</button>
</div>
);
}