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:
Computed with array operations:
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
createEffectinsteadComputed values can depend on other computed values, creating a dependency graph
Last updated