简体   繁体   中英

When it is React Hooks with Redux, must it be using selectors?

In the old days, when React and Redux was used, some people use selectors, some people don't.

(I think it is "reselect" npm package , but I am not sure).

However, when React has Hooks, I think we can use

useSelector()
useDispatch()

instead of all the mapStateToProps , mapDispatchToProps , connect(...)(Component) . However, must we make use of useSelector() ? Before, we have a choice to use selector or not to use it. Is it true that after we have React Hooks and Redux, then we have to use selectors?

Yes, you must use useSelector . And I think you have a bit of confusion there: If you were to use connect with mapStateToProps , you were always using a selector function there: mapStateToProps was that selector function, probably made off multiple sub-selectors that you might have been written inline or imported from somewhere.

You never "had the choice not to use a selector" though, if you wanted any value from the state. I think your concept of "what is a selector" is just a bit too strict.

You can use it two ways:

// in your slice file
export const someSelector = state => state.something;
// in your component file
import someSelector from './sliceFile';
// in your component
useSelector(someSelector)

or just inline:

useSelector(state => state.something)

Both of these are selectors , even when the second one looks a bit less like it.

One is just extracted into a function and the other one is an inline function. Both are totally okay to use and from a JS perspective, there is not a lot of difference between them.

As you mention reselect: reselect makes "memoized selectors", which is another concept on top of it. For that, you are free to use it or not use it, you're right there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM