Memo

Memo

Same interaction as Carousel, but fruit and first letter are derived with @memo from selected. Useful when you want stable derived values and explicit dependency tracking on the channel.

Backend

from rxdjango import ContextChannel, rx, action, memo


class CarouselMemoChannel(ContextChannel):

    FRUITS = ['banana', 'apple', 'orange']

    selected = rx[int](0)

    @action
    async def rotate(self):
        self.selected = (self.selected + 1) % len(self.FRUITS)

    @memo('selected')
    def fruit(self):
        return self.FRUITS[self.selected]

    @memo('fruit')
    def first_letter(self):
        return self.fruit[0]

Frontend

import React from 'react';
import { useChannel } from '@rxdjango/react';
import { CarouselMemoChannel } from '../../rx/memo/memo.channels';
import { Demo, Fields, Field, Button } from '../../components/demo';

export function MemoDemo() {
  const channel = useChannel(CarouselMemoChannel);

  return (
    <Demo>
      <Fields>
        <Field label="Selected">
          {channel.selected}
        </Field>
        <Field label="Fruit">
          {channel.fruit}
        </Field>
        <Field label="First letter">
          {channel.first_letter}
        </Field>
      </Fields>
      <Button onClick={channel.rotate}>
        Next
      </Button>
    </Demo>
  );
}

export default MemoDemo;