Skip to content

What is the "right" way to update an instance of a reactive thing based on props changing. #12720

Answered by kwangure
kwangure asked this question in Q&A
Discussion options

You must be logged in to vote

The latest version of the $state.link rune (before it was removed) used a pattern that solves our problem here cleanly.

The solution.
export function stateLink(getValue) {
	let wasLocal = false;
	let localState = $state(undefined);

	// Choose `localState` as the latest value if the mutation was local
	// Otherwise, choose the linked `getValue()` because the change was a reaction
	const linkedDerived = $derived.by(() => {
		const linkedValue = getValue();
		if (wasLocal) {
			wasLocal = false;
			return localState;
		}
		return linkedValue;
	});

	return {
		get current() {
			return linkedDerived;
		},
		set current(v) {
			wasLocal = true;
			localState = v;
		},
	};
}

The original exa…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
4 replies
@kwangure
Comment options

@kwangure
Comment options

@kwangure
Comment options

@brunnerh
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by kwangure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants