Skip to content

useDerived

useDerived makes a component follow the result of one call over server state, instead of every value the call could have read.

useDerived(body: () => Int): Int
src/once.ts2
const combatLevel = (): Int => {
const attack = useSkill(Skills.ATTACK);
const strength = useSkill(Skills.STRENGTH);
const defence = useSkill(Skills.DEFENCE);
const hitpoints = useSkill(Skills.HITPOINTS);
return (attack + strength + defence + hitpoints) / 4;
};
src/once.ts2
export const CombatRow = (): Component => {
const level = useDerived(() => combatLevel());
  • body: One call, whose arguments this render can name — a prop, a .map() row’s value, a constant. Not an expression around a call.

The call’s result, as an Int, and the component follows it.

  • The body is a single call (TS2E003). Put the arithmetic inside the function.
  • Inside a render body only (TS2E003).
  • The body’s arguments are things the render can name. Hand it a prop or a constant; do not read a useState cell inside it.
refused/use-derived.ts2
const level = useDerived(() => useSkill(Skills.ATTACK) + 1); // not a single call
src/once.ts2
const level = useDerived(() => combatLevel());

Following a switch that selects one variable

Section titled “Following a switch that selects one variable”
src/idiomatic.ts2
const threatOf = (which: Int): Int => {
switch (which) {
case 1: return 1;
case 2: return useServerState(Varps.POISON) > 0 ? 3 : 2;
default: return 3;
}
};
src/idiomatic.ts2
const threat = useDerived(() => threatOf(which));

Move the arithmetic into the function you call, and call it with the values the render can name.

My component redraws when something unrelated moves

Section titled “My component redraws when something unrelated moves”

Something else in the render reads that value directly.