@memo
@memo¶
This provides the exact same functionality as rx field example,
now using @memo decorator.
@memo receives a list of rx field names that are checked on any update to see
if the value needs to be recalculated.
Inspired by React’s useMemo()
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;