You are on page 1of 16

04.

State and Props in RN


Sungchul Lee
Agenda
First RN Expo Project

In this session, we learn about 1 State vs Props


State and Props

2 State

3 Props

4 Q&A
State vs Props
State vs Props
➢There are two types of “model” data in RN Component
– Props and state Props State
➢Props
– Component's configuration
– Immutable
<Component props_name
➢State = “props_value”
– The state starts with a default value when a Component mounts
and then suffers from mutations in time (mostly generated
from user events)
– keep track of information between renderings the
component itself can create, update, and use state.
State vs Props – cont
➢Props
– For user to use view
– Read-only (user side)
– Can not be modified (user side)
➢State
– For implementing
– Change can be asynchronous
– Can be modified
State
State
➢State of a component is an
object that holds some
information that may change
over the lifetime of the
component.
– state hold information for view
Change Text (without State)

Changed?
useState() Reference: https://reactjs.org/docs/hooks-state.html

➢Set State on component


➢useState() function
– Return two items
➢Tip: What Do Square Brackets Mean? (Example)
– const [fruit, setFruit] = useState('banana’);
– JavaScript syntax is called “array Destructuring”.
• It means that we’re making two new variables fruit and setFruit,
where fruit is set to the first value returned by useState, and setFruit
is the second. It is equivalent to this code:
• var fruitStateVariable = useState('banana'); // Returns a pair
• var fruit = fruitStateVariable[0]; // First item in a pair
• var setFruit = fruitStateVariable[1]; // Second item in a pair
useState() with Code
➢Import useState from ‘react’
➢Re-rendering view page
– onPress Event
• Perform changeState function
➢Initialize state varibles
– useState(init)
• Return two items
– Variable
– Set function
– Use variable
• {variable name}
useState()
➢Changed value by onPress
➢When sample: false

➢When sample: true


Props
Props
➢When React sees an element representing a user-defined
component, it passes JSX attributes and children to this c
omponent as a single object. We call this object “props”.
– https://reactjs.org/docs/components-and-props.html
➢Inheritance from Parent
– But, can not change value
Props Example – propsChild.js
➢Create new file (propsChild.js)
– Child component
– Get data from Parent
component (App)
➢Props
– Holds parent’s data
– {props.inputText()}
– {props.changeState}
Props Example – App.js
➢Import child component
– Import PropsChild from ‘Path/file’
➢Pass Data to child
– sText
• Pass variable
– cState
• Pass function

Click
Q&A

You might also like