Ryan Wilkins
Ryan Wilkins

Reputation: 147

Do useSelector() and useDispatch() replace mapStateToProps() and mapDispatchToProps()?

I'm new to React & Redux, and many of the guides I've been using are a couple years old. It seems that Hooks in both React and Redux are relatively new, and the general recommendations I've seen are to replace class Components in React with functional components and useState().

What I'm unclear on as I go through Redux exercises is if mapStateToProps(), mapDispatchToProps() and connect() are still relevant, or if I can now replace that with the useSelector() and useDispatch() hooks.

Currently, with the mapStateToProps() and mapDispatchToProps() setup, I have a parent component sending my Redux store state to multiple children, through multiple levels. Whenever I add a new state variable into my store this involves drilling that new state through all these components, made doubly cumbersome by the fact that I'm using Typescript and have to update all my ownProps types.

One option would be to connect() each child component directly to the store. Could I instead use useSelector() and useDispatch() for each of the children components where I actually use the state variable? What would be the downsides to this?

Thank you!

Upvotes: 5

Views: 4988

Answers (2)

markerikson
markerikson

Reputation: 67489

Yes, as per the other answer, the React-Redux hooks API replaces the existing connect API, and we specifically recommend using the hooks API as the default:

Part of that is that we recommend using TypeScript with Redux, and the hooks API is a lot simpler to use with TS than connect is:

Upvotes: 6

zjeremic
zjeremic

Reputation: 41

Yes. With useSelector and useDispatch you can completely eliminate Container whose purpose was to map state and actions into your child component. You just have to assign state to variable inside of your component and dispatch action to redux, e.g. like in this example:

export default function AccountScreen(props) {
   const user = useSelector(state => state.account);

    const handleSubmit = () => {
        dispatch(updateProfile(user._id, firstName, lastName, alergies, dob, medicalCondition));
        props.navigation.navigate('HomeTab');
    }

Upvotes: 4

Related Questions