createComputed
Creates a computed value that automatically updates when its dependencies change.
Signature
function createComputed<T>(fn: () => T): Signal<T>;
Parameters
fn: () => T
- A function that computes the value. This function will be re-executed whenever any signals it accesses change.
Returns
Signal<T>
- A getter function that returns the computed value
Example
const [firstName, setFirstName] = createSignal("John");
const [lastName, setLastName] = createSignal("Doe");
const fullName = createComputed(() => {
return `${firstName()} ${lastName()}`;
});
console.log(fullName()); // "John Doe"
setFirstName("Jane");
console.log(fullName()); // "Jane Doe"
Advanced Usage
Idioms and Patterns: Reactive Patterns
Computed with conditional dependencies:
const [withEmail, setWithEmail] = createSignal(false);
const [user, setUser] = createSignal({
name: "John Doe",
email: "john.doe@pm.me",
});
const author = createComputed(() => {
if (withEmail()) {
return `${user().name} <${user().email}>`;
}
return user().name;
});
Computed with array operations:
const [tasks, setTasks] = createSignal([
{ id: "I", text: "Inhale", completed: true },
{ id: "E", text: "Exhale", completed: true },
{ id: "R", text: "Repeat", completed: false },
]);
const completedCount = createComputed(() => {
return tasks().filter((task) => task.completed).length;
});
const uncompletedCount = createComputed(() => {
return tasks().length - completedCount();
});
Behavior
Automatically tracks all signals accessed within the computation function
Re-executes only when dependencies change
Uses
Object.is()
to prevent unnecessary updatesLazy evaluation - only computes when the value is actually needed
Can be used as dependencies for other computed values or effects
Performance Notes
Computed values are cached and only re-computed when dependencies change
Avoid side effects in computed functions - use
createEffect
insteadComputed values can depend on other computed values, creating a dependency graph
Last updated