0
0
DenoHow-ToBeginner ยท 4 min read

How to Use Signals in Fresh Framework in Deno

In Fresh, use signal from @preact/signals to create reactive state variables that update the UI automatically. Wrap your state with signal(initialValue) and access or update it with .value to trigger re-renders.
๐Ÿ“

Syntax

Signals in Fresh are created using the signal function from @preact/signals. You create a signal by passing an initial value. Access or update the signal's value using the .value property. When the value changes, Fresh automatically updates the UI where the signal is used.

  • signal(initialValue): Creates a reactive signal.
  • signal.value: Gets or sets the current value.
typescript
import { signal } from "@preact/signals";

const count = signal(0);

console.log(count.value); // Access current value
count.value = 5; // Update value and trigger UI update
Output
0
๐Ÿ’ป

Example

This example shows a simple Fresh component that uses a signal to track a counter. Clicking the button updates the signal's value, and the UI updates automatically without manual DOM handling.

tsx
import { signal } from "@preact/signals";

export default function Counter() {
  const count = signal(0);

  return (
    <main>
      <h1>Count: {count.value}</h1>
      <button onClick={() => count.value++}>Increment</button>
    </main>
  );
}
Output
A webpage showing "Count: 0" and a button labeled "Increment". Each click increases the count by 1 and updates the displayed number instantly.
โš ๏ธ

Common Pitfalls

  • Forgetting to use .value when reading or updating signals causes no UI updates.
  • Directly mutating objects inside signals without replacing the whole object won't trigger updates.
  • Using signals outside components or without importing signal properly leads to errors.
typescript
import { signal } from "@preact/signals";

// Wrong: updating signal without .value
const count = signal(0);
count = 5; // This does NOT update the signal

// Right: update with .value
count.value = 5; // Correct way to update and trigger UI
๐Ÿ“Š

Quick Reference

  • Create signal: const state = signal(initialValue);
  • Read value: state.value
  • Update value: state.value = newValue;
  • Use in JSX: {state.value} to auto-update UI
โœ…

Key Takeaways

Use signal from @preact/signals to create reactive state in Fresh.
Always access and update signal values with the .value property to trigger UI updates.
Signals automatically update the UI when their value changes, no manual DOM work needed.
Avoid mutating objects inside signals directly; replace the whole object to trigger updates.
Import signal correctly and use signals inside components for proper reactivity.