Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapStateToProps for functional component

Is there any function similar to mapStateToProps so that we can connect Redux state to the functional component in React?

Is passing the state as props from parent component the only solution?

like image 775
Sumit Avatar asked Oct 17 '18 14:10

Sumit


People also ask

Can I use mapStateToProps in functional component?

You can definitely use mapStateToProps with a functional component, the same way you would with a class component.

Why do we use mapStateToProps in functional component?

As the first argument passed in to connect , mapStateToProps is used for selecting the part of the data from the store that the connected component needs. It's frequently referred to as just mapState for short. It is called every time the store state changes.

Can I use mapDispatchToProps in functional component?

Yes. You can skip the first parameter by passing undefined or null . Your component will not subscribe to the store, and will still receive the dispatch props defined by mapDispatchToProps .

Can we use mapStateToProps in class component?

In class components mapStateToProps works the same as functional components, I feel there are only differences in some syntax or calling approaches.


2 Answers

You can definitely use mapStateToProps with a functional component, the same way you would with a class component.

function MyComponent({ propOne }) {   return <p>{propOne}</p> }  function mapStateToProps(state) {   return { propOne: state.propOne }; }   export default connect(mapStateToProps)(MyComponent); 
like image 189
David Avatar answered Sep 28 '22 10:09

David


react-redux now has a useSelector method. That's a much cleaner approach for functional components that employ hooks. See: https://react-redux.js.org/next/api/hooks#useselector

like image 26
Jason Rice Avatar answered Sep 28 '22 10:09

Jason Rice