atlassian / react-sweet-state

Shared state management solution for React

Home Page:https://atlassian.github.io/react-sweet-state/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Shortcut for "action only" selectors

anacierdem opened this issue · comments

This has become a pattern we use very frequently;

export const useStoreActions = createHook(store, {
  selector: () => null,
});

// Then we use it as;

const [, actions] = useStoreActions();

For the places where we only need to use the actions and don't want the component get updated because of this store. I think the library can just export a useStoreActions hook that does that by default. (Also see here for a similar API though I think the function argument is not very useful in case of **react-sweet-state.) It might also enable a few optimizations internally? That might not be possible without knowing which store to use though so maybe we could have;

export const useStoreActions = createActionsHook(store);

Which is probably not very beneficial.

Not something very important, but would be a nice addition to save many stores from a null selector. If only there was a way to use a direct hook import.

const actions = useStoreActions(store) might be an option for a direct import solution as well but it would be a weird API signature considering other things.

So, there is already a shorthand version that enables few more performance optimisations:

export const useStoreActions = createHook(store, { selector: null });

By defining selector to be actually null, we can fully opt-out from subscribing to updates (while a function that returns null still triggers the subscription, but not the re-render).

I guess now that hooks are widely popular and we see actions only hooks being often used too, we could provide a shorthand like createActionsHook. I'll check how much code we would need to add in order to do that and just return actions (instead of an array).

About useStoreActions(store), we'd rather not go down that path mostly due to the way we consider Store an implementation detail of the hook, and providing it as argument might raise questions/complexity around what happens if that changes.