DocsBlog
  • 1.1.2

  • light

    dark

    system

    Switch mode
  • Cerberus

    Acheron

    Elysium

Get Started
Components
Data Grid
Signals
Styling
Theming

Get Started

OverviewReactivityData FetchingStores

Primitives

createSignalcreateQuerycreateMutationcreateComputedcreateEffectcreateStoreContextbatch

Hooks

useQueryuseMutationuseReaduseSignal

Components

ReactiveText

On this page

  • Edit this page on Github

Computing Signal Values

Learn how to combine signals to create a single value in React.

  • source
import { createComputed } from '@cerberus/signals'

Usage

Sometimes you may want to create a new signal that is computed from other signal values. This is where the createComputed primitive comes in.

This API is similar to the native useMemo hook from React without the need for providing a depedency Array.

In this example, we create a computed signal based on two raw signals. Likewise, we utilize the createEffect primitive which sets the signal value without React getting involved.

Note

In order for createComputed to track signal subscriptions, it is required that Accessors are used in the body.

API

createComputed accepts a callback function and returns the value in a form of a Signal Accessor.

Important: be sure to use Accessor getters not values within a createComputed primitive. Ignoring to do so will cause stale values that will not be updated.

Copy
'use client'

import { HStack, Stack } from '@/styled-system/jsx'
import { Button, Text } from '@cerberus/react'
import { createComputed, createEffect, useSignal } from '@cerberus/signals'

export function BasicDemo() {
  const [count, setCount, getCount] = useSignal<number>(0)
  const [_isEven, setIsEven, getIsEven] = useSignal<boolean>(false)

  const info = createComputed(() => {
    return `${getCount()} is ${getIsEven() ? 'even' : 'odd'}`
  })

  createEffect(() => {
    setIsEven(getCount() % 2 === 0)
  })

  return (
    <HStack gap="xl" w="3/4">
      <Button onClick={() => setCount(count + 1)}>Increment</Button>

      <Stack direction="column" gap="xs">
        <Text>Count: {count}</Text>
        <Text>Double Count: {info()}</Text>
      </Stack>
    </HStack>
  )
}

Count: 0

Double Count: 0 is even