blackr1234
blackr1234

Reputation: 1476

Does Redux’s useSelector Hook Method Return Reference to the Data Model Instead of a New Object?

I am a beginner in React and Redux. I am using react 16.9 with redux 4.0.4 and react-redux 7.1.1.

I notice that I can directly access the underlying Redux data model (objects in store) without dispatching actions.

Consider the following component:

import React from 'react';
import { useSelector } from 'react-redux';

function MyComponent(props) {
    const obj = useSelector(state => state.objReducer);
    obj.newProperty = 'foo';

    return <div />;
}

When the component is mounted, newProperty: foo will be added to objReducer.

My understanding is that we should dispatch actions to reducers in order to make changes to the underlying data model. Also, as stated here, "With useSelector(), returning a new object every time will always force a re-render by default." So useSelector should return a new object instead of the actual data object, right?

I am wondering why React-Redux's useSelector gives developers access to the actual data.

Upvotes: 2

Views: 1439

Answers (1)

Matthew Barbara
Matthew Barbara

Reputation: 3962

You are mutating the global state with obj.property = 'foo'; which is an anti-pattern.

useSelector is the equivalent to mapStateToProps in the "old" react-redux, which was used solely to access the state within a component.

If you change the state by mutations, like you are doing, the reference of the state will not change and your components listening to this state will not re render.

On the other side, if you use useDispatch() you have to ensure that you are not mutating the state there too, by returning a new object rather than mutating the existing one.

Upvotes: 3

Related Questions