1

zutand doc mentioned that you can use selector if a selector doesn't depend on the scope and provide the example below

enter image description here

I didn't understand the doesn't depend on scope part. Could someone provide some examples of when the state depends on the scope so that the selector should not be used?

Thanks!

sean0923
  • 105
  • 1
  • 6
  • 3
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Sysix Apr 25 '21 at 23:46
  • It means that the selector function only depends on the state variable passed to it, not any other variables inside Component() so it can be pulled up into a function outside of the component. It's not specific to zustand. – Andy Ray Apr 25 '21 at 23:47

1 Answers1

0

All that means is the selector is a function that only consumes a state object and thus has no external dependencies.

Could someone provide some examples of when the state depends on the scope so that the selector should not be used?

Scope wouldn't affect when or where a selector function could be used, but rather where it can be declared. Selector functions without dependencies other than state can be declared external to any component using them.

You could write a selector function that also references a value defined in the component, so the value would be an external dependency.

const MyComponent = () => {
  const value = ......;

  const selector = state = {
    // use enclosed value to compute returned value from state
    ... do something with value
  };

  const valueFromState = useStore(selector);

  ...
Drew Reese
  • 165,259
  • 14
  • 153
  • 181