$effect
$effect is used to perform side effects (like logging, manual DOM manipulation, or API calls) whenever reactive dependencies change.
Overview
ts
import { $effect } from "oberry";
const stop = $effect(() => {
// This code runs immediately, and again whenever
// any reactive values used here change.
return () => {} // a cleanup function that runs before each re-execution and on disposal
});
stop(); // Stops the effectExamples
Syncing to LocalStorage
ts
const theme = $ref(localStorage.getItem('theme') || 'light');
$effect(() => {
localStorage.setItem('theme', theme());
$('body').class.remove('light', 'dark').class.add(theme());
});Tracking Document State
ts
const cartItems = $ref([]);
$effect(() => {
const count = cartItems().length;
document.title = `Cart (${count})`;
});Auto-updating clock with cleanup
ts
const stop = $effect(() => {
console.log("Effect started");
const timer = setInterval(() => {
time(new Date().toLocaleTimeString());
}, 1000);
// Return a cleanup function to stop the timer before next run or on disposal
return () => {
console.log("Cleaning up previous timer");
clearInterval(timer);
};
});
stop(); // Output: Effect started; Cleaning up previous timer