0

I'm looking for some guidance on the actual usage of lazy selectors vs dynamic selectors in NGXS. I understand the difference in syntax but I'm actually unclear on where I should prefer one over the other since both allow passing arguments to a selector. Are there any performance gains to be had in one case or the other? I've read the appropriate documentation but feel like I still don't get it.

See this snippet from this Stackblitz for a lazy selector followed by the same selector in dynamic form.

export class ZooStateQueries {
  @Selector([ZooState.animals])
  static animalOfType(animals: string[]) {
    return (type: string) => {
      return animals.filter(s => s.indexOf(type) > -1);
    };
  }
  
  static animalOfType_Alternative(type: string) {
    return createSelector([ZooState.animals], (animals: string[]) => {
      return animals.filter(s => s.indexOf(type) > -1);
    });
  }
}

No actual usage issue, more of a clarification question. Thank you for any help!

1 Answer 1

1

Lazy selectors are way more powerful in my opinion because they allow you to further compose them into other selectors and bind the parameter to other information from another part of your state.

You can also very easily create a dynamic selector from a lazy selector, but not the other way around.

A dynamic selector is more for a fixed sort of argument binding for your selector. It is really just a selector factory that takes a parameter. The dynamic nature of it is the fact that you can dynamically create new selectors for your app.

Dynamic selectors are only a good fit when the argument is provided up front by your app, has specific domain utility, and doesn't come from user input. Even then, I would create a lazy selector and wrap it with a dynamic selector at the last responsible moment.

Performance wise, a dynamic selector has the advantage of isolated memoization for each created selector, but this very slight advantage is really negligible in the grand scheme of things.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for taking the time to answer my question Mark, that's exactly what I was looking for. Have a good day :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.