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): IntReference
Section titled “Reference”useDerived(body)
Section titled “useDerived(body)”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;};export const CombatRow = (): Component => { const level = useDerived(() => combatLevel());Parameters
Section titled “Parameters”body: One call, whose arguments this render can name — a prop, a.map()row’s value, a constant. Not an expression around a call.
Returns
Section titled “Returns”The call’s result, as an Int, and the component follows it.
Caveats
Section titled “Caveats”- 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
useStatecell inside it.
const level = useDerived(() => useSkill(Skills.ATTACK) + 1); // not a single callFollowing a calculation’s answer
Section titled “Following a calculation’s answer” const level = useDerived(() => combatLevel());Following a switch that selects one variable
Section titled “Following a switch that selects one variable”const threatOf = (which: Int): Int => { switch (which) { case 1: return 1; case 2: return useServerState(Varps.POISON) > 0 ? 3 : 2; default: return 3; }}; const threat = useDerived(() => threatOf(which));Troubleshooting
Section titled “Troubleshooting”The body must be a single call
Section titled “The body must be a single call”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.