Redux: Use selector

Tram Ho

As you’ve learned through Redux you’ve probably heard “keep the state the simplest, and use it when you need it,” as part of that lesson you may have also used the redux selector .

A selector function takes the input state and returns a desired value based on that state . For example

You can use the selector everywhere as long as it’s a component , a selector usually starts with a prefix get [something] or select [something] or it can be a suffix [something] selector .

The rendering:

  • When an action is dispatch , the useSelector will perform a comparison between the previous result and the current one, otherwise the component is forcibly re-render .
  • useSelector uses === comparison, not the shallow compare method
  • Reasons for using useSelector :
    • Reuse, selector can be used in many places, many different component without re-declaring
    • Lean, we have a state car containing name , brand , year , if you want to get brand , just getBrandCar selector is easy to understand.
    • Update, when the redux store structure changes, we just need to update the selector again


Since the selector uses the “===” comparison method, if the array or object returned through the computation, the component will be trigger re-render . While re-render even though the data not changed, the selectFilteredSortedTransformedData function is still called:

How to solve the problem, using reselect :


  • If the selector has an input as a component prop , put the selector outside of the component
  • Multiple instance of component : When a selector is used in multiple instance of a component and also depends on prop , e.g.

    What we need to do now is make sure each instance component has a separate instance selector , as in the above example it is not correct because the two instance are pointing to the same instance selector .

    Solution, use useMemo

    And now each instance of CarDetails has an instance of a different selector
Share the news now

Source : Viblo