user1941537
user1941537

Reputation: 6675

Understanding the props concept in React

While I'm learning React, it's always said that you should keep your state in the parent component and pass them as props to its children.

But in the real world, whenever I start building a react app, I end up passing data from a child component to its parent.

For example, if I have to implement a form somewhere in my react app, I create an extra component for it (for example, FormComponent) and import it in my App component.

But now, I have to pass the form data form the FormComponent to the App component. In other words, from the child component (FormComponent) to the parent (App component).

And this was just an example. Usually, I always end up in situations where I have to pass data from child to parent rather than the other way around.

Do I misunderstand the concept of passing props completely? If we stay with the above example, is my approach, right?

Upvotes: 4

Views: 143

Answers (2)

Omar Jribi
Omar Jribi

Reputation: 89

1- In your case you can pass a function ( Example: handleSubmit() ) through props from parent to child. And so when this function is called the child's data would be hundled from the parent. you can use this doc page to inspire your code.

2- Otherwise you can use react redux, and then you can hundle all data at any component in your project using one global state called redux store.
want to learn more about react redux click here.

3- Have a nice day ^_^ .

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53874

You can't pass data from child to parent as in React, The Data Flows Down.

So usually you pass callbacks from parent to its children, but the state remains in the parent.

This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

If you in a situation where the code becomes unreadable, unmaintainable, you should consider Lifting the State Up.

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.

Aside from it, a common anti-pattern is Prop Drilling, Context API, and many state libraries like Redux, MobX, and Recoil trying to solve such problems with some extra features.

Upvotes: 4

Related Questions