Effects
Run code when state changes with createEffect
.
createEffect
is a powerful feature in Olova that allows you to run side effects in response to state changes. This is particularly useful for tasks like logging, fetching data, or updating the DOM outside of the normal rendering process.
Here's a cool example using createEffect
:
jsx
import { createSignal, createEffect } from "olova";
function Greeting() {
const [name, setName] = createSignal("Bob");
// Effect to log a message whenever the name changes
createEffect(() => {
console.log("Hello,", name());
});
return (
<div>
<h1>Hello, {name()}!</h1>
<button onClick={() => setName("Alice")}>Change Name to Alice</button>
</div>
);
}
export default Greeting;
Explanation
- Importing
createEffect
: We importcreateEffect
fromolova
to handle side effects. - Creating a Signal: We use
createSignal("Bob")
to initialize a name state. - Using
createEffect
: ThecreateEffect
function runs a side effect (logging to the console) whenever thename
signal changes. - Rendering the UI: The component displays a greeting and a button to change the name. When the button is clicked, the name changes, triggering the effect.
This example demonstrates how createEffect
can be used to perform side effects in response to state changes in Olova, ensuring that your application can react dynamically to user interactions.
jsx
const [name, setName] = createSignal("Bob");
createEffect(() => {
console.log("Hello,", name());
});
setName("Alice");