Ad

Redux Action Creators State Access Best Practices

- 1 answer

In redux, when we need to access a state property that is not directly related to a componentProps but is triggered from this component (ie: a grand parent component id that is stored in the state) should we try to pass this part of the state to action creators from the component that triggers the event ie:

onClick={() => doSomething(grandParentId)}

----

function doSomething(grandParentId) {
  console.log(grandParentId)
}

or should we get the data from getState with redux-thunk?

onClick={doSomething}

----

function doSomething() {
  return (dispatch, getState) => {
    console.log(getState().grandParentId)
  }
}

I know that the answer sounds like the first approach is more proper, but I somehow feel that getState with redux-thunk can lead to bad practices and I would like to know when I should use it or not.

Ad

Answer

If you already have that information in your component, I don't see why not passing it along to your action creator. The flow of data is much easier to follow this way, in my opinion.

I would take advantage of getState() only when I need to access part of the state tree that I wasn't able to pass via action creator.

Ad
source: stackoverflow.com
Ad