Reputation: 20581
I have a React User Profile page that retrieves User object from back-end. User profile object contains a lot of fields (about 30). I learnt that it is good practice in Typescript to create IUser
interface and cast retrieved User object (JSON data) to IUser
.
User page is splitted to many subcomponents, and each component needs only some set of fields from User object (one component shows user general info, another shows user related post etc.).
Since each of sub-component needs only some set of user fields, I forced to duplicate all required fields in Props
of each sub-component. That seems to me like over-engineering and leads to a lot of code.
Another options is to pass whole user
object to each subcomponent. This way it will work, but that also smells bad, because I'm passing props to component that actually don't use them.
What is elegant way to solve this problem?
Upvotes: 1
Views: 452
Reputation: 21317
React is all about data flowing down in the component's tree. If you come to a point where state is fragmented you can always use redux. Some apps are too complex and nested to make good use of props. Take a look in hooks, they made possible to reuse stateful logic, but if what you want is really share state, use props
or some state management tool like redux. Do not use Context in this case
Upvotes: 1
Reputation: 35
You could use the context API if your version of react allows it.
The Context API allows you to avoid props drilling as it is called and it can probably be a good solution to your problem.
I think this article will be able to help you : https://adamisntdead.com/reacts-context-api/
Upvotes: 0