On State and Props

·

2 min read

Understanding props and state in react native components, from a conceptual and practical level, is one thing pretty much all RN developers will tell you is absolutely necessary to have. This article is to give a high level overview of the topic and break it down in some specific use-case scenarios as I have seen.

Sample questions: what are props; how do you pass data with props; what is state? How do you update a component’s state? What happens when state changes? Can I use state in every component? What are the differences between props and state

The RN docs does a pretty good job of explaining this in basic terms to be fair so please go (there) before continuing this. As described there, props are short for properties and simply help to pass data between React components (typically from parent to child.) React has a unilateral data flow(aka One-Directionwink wink), typically from parent to child.

(Large example)

One thing that got a bit difficult in understanding props was how to pass data from child to parent. I hear your woes too. Most things I found online couldn’t help in understanding this from a contextual area, but I did. Let’s use an instance: (instance) The main way of passing from child to parent is using a callback function

(Large example & explanation)

State-

State is another big concept in React Native. It is basically an object for storing and managing data. So unlike props, components cannot pass data with state, but they can create and manage it internally. Now, I understand that most examples on the docs use class components. And that just won’t do...so here’s some example using functional components as that is what is most in use today(2021) anyway.

In a real application, you probably won't be setting state with a timer. You might set state when you have new data from the server, or from user input. You can also use a state container like Redux or Mobx to control your data flow. In that case you would use Redux or Mobx to modify your state rather than calling setState directly.