Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS good practices using Hooks and Redux. Should I use useSelector in each component, or I should pass via props?

I should use the same useSelector in each child component or I should pass the useSelector via props?

Both examples below works, I just want to know what is the best practice.

Example passing via props:

const FatherComponent = () => {
 const userId = useSelector((state) => state.user.id);

 return (
   <ChildComponent userId={userId} />
 )
}

const ChildComponent = ({userId}) => {
 return (
 <>{userId}</>
)
}

or example repeating the useSelector:

const FatherComponent = () => {
 const userId = useSelector((state) => state.user.id);

 return (
  <ChildComponent />
 )
}

const ChildComponent = () => {
 const userId = useSelector((state) => state.user.id);

 return (
  <>{userId}</>
 )
}
like image 889
Danilo Cunha Avatar asked May 07 '20 15:05

Danilo Cunha


1 Answers

Prefer having more UI components subscribed to the Redux store and reading data at a more granular level

Just for the completeness, above is the recommendation from official redux site.

Full credits to Nicholas Tower who pointed to the page in the comments section.

Prefer having more UI components subscribed to the Redux store and reading data at a more granular level. This typically leads to better UI performance, as fewer components will need to render when a given piece of state changes.

For example, rather than just connecting a component and reading the entire array of users, have retrieve a list of all user IDs, render list items as , and have be connected and extract its own user entry from the store.

This applies for both the React-Redux connect() API and the useSelector() hook.

From the link - https://redux.js.org/style-guide/style-guide#connect-more-components-to-read-data-from-the-store

like image 118
Sateesh Pagolu Avatar answered Sep 30 '22 04:09

Sateesh Pagolu