Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

update: New Hooks API #4

Merged
merged 3 commits into from
Oct 8, 2021
Merged

update: New Hooks API #4

merged 3 commits into from
Oct 8, 2021

Conversation

idreyn
Copy link
Contributor

@idreyn idreyn commented Oct 8, 2021

This PR updates the way reactive attributes access hooks like useState and useEffect. Previously, these values were bound to this in an attribute hook:

function useTicker(this: Hooks) {
	const { useState, useEffect } = this;
	const [ticks, setTicks] = useState(0);

	useEffect(() => {
		const interval = setInterval(() => setTicks((t) => t + 1), 1000);
		return () => clearInterval(interval);
	}, []);

	return ticks;
}

Because TypeScript forces you to annotate this as an argument to the function, this is more confusing than it is slick. It also forces you to use the function keyword to define your hook functions, which, eh. This change introduces global versions of hook primitives that are exported from the package, which are used as follows:

import { useState, useEffect } from '@pubpub/prosemirror-reactive';

const useTicker = () => {
	const [ticks, setTicks] = useState(0);

	useEffect(() => {
		const interval = setInterval(() => setTicks((t) => t + 1), 1000);
		return () => clearInterval(interval);
	}, []);

	return ticks;
}

This matches the React API and reduces the number of things you have to know to write a valid attribute hook.

@idreyn idreyn changed the title New hooks api update: New Hooks API Oct 8, 2021
@idreyn idreyn merged commit e9d3aec into main Oct 8, 2021
@idreyn idreyn deleted the new-hooks-api branch October 8, 2021 01:52
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant