ffxsam
ffxsam

Reputation: 27753

React, conceptual concern: Children vs (grand)parents maintaining states

I've heard that in React, it's best to keep states as high up as possible, and not have them on children. Is that generally true? It seems to make sense to me to have children be self-aware components that maintain their own states. Can someone explain this concept and why it's better to have states on parents?

I'll give an example of something I'm working on now:

I have a file uploader where there's a file dropzone that, when a file is dropped on it, it tells the parent that file(s) were dropped, which in turn sets a state containing the list of files, which is passed down as a prop to an upload queue component, which contains several FileUpload components (progress bars/upload processes). Those FileUpload components have their own progress state. It doesn't seem to make sense to track that any higher up.

Maybe someone can shed more light on this methodology.

Upvotes: 1

Views: 49

Answers (2)

nathancahill
nathancahill

Reputation: 10850

I don't know if I've heard "keep the state as high as possible", but rather, keep the state in a parent whose children share the same state. How you're doing it sounds right to me.

Upvotes: 1

Cristian Sava
Cristian Sava

Reputation: 106

You are talking about the Flux application architecture that has unidirectional data flow.

I would suggest you to read the official documentation about Flux and understand the diagram about data flow. Basically, you have a main component that holds the functionality of part of your app, like a file uploader, and only this component receives data from Store by updating it's own state. The main component pass that data to the children via props. A children should never update his own state, if you need to update something in a children component, you emit an action to the store that will update the state of main component.

Upvotes: 0

Related Questions