H
H
hellcaster2021-01-18 18:24:06
React
hellcaster, 2021-01-18 18:24:06

How to correctly pass data to a component?

Hey! Faced with, perhaps, a very obvious and banal question: how to pass data to a component ?
So far, I see 2 ways: through props (with App to my component) and redux (mapStateToProps, mapDispatchToProps) (we'll skip the Context for now).

Case 1 (props (with App to my component))
For example, I have a list of products on a website. In order for my product list to receive all the data, I must pass all the data through App, Main, SomeWrapper, SomeOtherWrapper, GoodsList (figurative example), make no mistake anywhere and only then output. Now imagine that I need to add onClick to GoodsItem => I need to pass onGoodsItemClick through all components again, and then fix the tests, because PropTypes will swear, and PropTypes itself. Doesn't it seem a little complicated, routine and not very technological?

Case 2 (redux (pass to the component only what is needed via mapStateToProps, mapDispatchToProps))
Well, let's consider the 2nd case: the component for sorting offers. I wrote a connect for my component, the functions look like this:

const mapStateToProps = (state, ownProps) => ({
  ...ownProps,
  sortType: state.sortType,
  allOffers: state.allOffers // allOffers нужен только для mapDispatchToProps
});

const mapDispatchToProps = (dispatch) => ({
  onSortChange: (allOffers, sortType) => {
    dispatch(ActionCreator.changeSortType(sortType));
    dispatch(ActionCreator.sortOffers(allOffers, sortType)); // allOffers используются только тут
  }
});


Here I have to get allOffers only in order to later pass it to mapDispatchToProps to sort offers (possibly a mistake at this stage. As far as I know, ActionCreator does not have access to the store and should only work on parameters). Why do I need to receive data that is not even rendered on the page?

What do React programmers do in this case? Use only one method? Use 2, but in different cases? Go in the middle with modifications? Do they use method 3?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander N, 2021-01-18
@wooly

Forget about the heavy and bulky redux, take mobx to watch videos on YouTube and use it. Perform all operations in the store and display only the result in the component. The amount of code is extremely small. wrap the component in an observer, it will easily track everything

D
Denioo, 2021-01-23
@Denioo

Forget about mapState, mapDispatch, it's already pretty outdated. Use redux hooks: useSelector, useDispatch. Everything is pretty simple there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question