Files
mobx-utils/src/expr.ts
Michel Weststrate f6d4a7d615 Fixing stuff
2018-03-06 21:46:02 +01:00

24 lines
1.0 KiB
TypeScript

import { computed, _isComputingDerivation } from "mobx"
/**
* expr can be used to create temporarily views inside views.
* This can be improved to improve performance if a value changes often, but usually doesn't affect the outcome of an expression.
*
* In the following example the expression prevents that a component is rerender _each time_ the selection changes;
* instead it will only rerenders when the current todo is (de)selected.
*
* @example
* const Todo = observer((props) => {
* const todo = props.todo;
* const isSelected = mobxUtils.expr(() => props.viewState.selection === todo);
* return <div className={isSelected ? "todo todo-selected" : "todo"}>{todo.title}</div>
* });
*
*/
export function expr<T>(expr: () => T): T {
if (!_isComputingDerivation())
console.warn("'expr' should only be used inside other reactive functions.")
// optimization: would be more efficient if the expr itself wouldn't be evaluated first on the next change, but just a 'changed' signal would be fired
return computed(expr).get()
}