Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux useSelector with Conditional statement

I need to get Redux store data but not always and different data for each component instantiate. How can I use useSelector with Conditional statement?

The component should get data from store only when some child components are rendered and also different data each time depending on the child component.

like image 847
Yuval Levy Avatar asked Mar 03 '23 11:03

Yuval Levy


1 Answers

useSelector takes in a callback that has access to the redux state as an argument

so assuming you control whether the child component is rendered in a boolean flag called isComponentRendered, and want to select data when it is true and else nothing, you could try the following:

const data = useSelector(state => {
   if(state.isComponentRendered) {
       return state.data
   }
   return null;
})
like image 149
canecse Avatar answered Mar 17 '23 18:03

canecse