Ref
APIA type safe and functional way to handle mutable references to value
Motivation
The Ref
type represents a mutable value that can be shared over the program.
Usage
import { Ref } from '@w5s/core';
const counter = Ref(0);
const increment = () => {
counter.value = counter.value + 1;
};
increment();// counter.value === 1
increment();// counter.value === 2
Read / Write value
It is possible read and / or write Ref
value, using Ref
namespace
const counter = Ref(0);
// Use `Ref.modify` when mapping previous value to new value
const increment = () => Ref.modify(counter, (current) => current + 1);
// Use `Ref.write` when setting a value
const reset = () => Ref.write(counter, 0);
Coding Guide
astuce
Always Ref in the following cases
- When you want to mutate a value
- Prefer
Ref
overlet
- ⚠️
let
could be used for internal state, when performances are critical
- Prefer
- When you want to share a mutable value across multiple parts of your code
astuce
Always use immutable values everywhere and use Ref
for mutations
// ✓ GOOD
interface State {
readonly name: string,
readonly total: number,
readonly items: ReadonlyArray<string>,
}
const state = Ref<State>>({
name: 'pet store',
total: 1,
items: ['dog']
});
const addItem = (state: typeof state, item: string) => {
Ref.modify(state, (current) => ({
...current,
total: current.total + 1,
items: [...current.items, item],
}));
};
// ✓ BAD
const state = {
total: 1,
items: ['dog']
};
const addItem = (state: typeof state, item: string) => {
state.total += 1;
state.items.push(item);
};