-
0001 - Props / State2021/개발 2021. 1. 10. 21:33
www.udemy.com/course/the-complete-react-native-and-redux-course/
Props: System to pass data from a parent to a child
State: System to track a piece of data that will chanege over time. If that data changes, our app will 'rerender'.
Props는 부모자식간 데이터 전달의 목적이고 State는 데이터 변경을 추적한다
State를 사용하기 위해서는 useState라는 React Hook을 사용함.
-> State Hook이라고 불리는듯 함 (ko.reactjs.org/docs/hooks-state.html)
import React, { useState } from 'react'; ~~ const example = () => { const [count, setCount] = useState(0); return ( <View> <Button onPress={() => setCount(count + 1)} /> <Button onPress={() => setCount(count - 1)} /> <Text>{count}</Text> </View> ) }
Flow
1. App init
2. Counter state Init => useState(0)
3. User taps Button, onPress callback runs
4. callback calls setCount() and update value
5. Rerender
Few Notes on State
- We are using function-based state in a functional component.
React also has class-based components that have access to state. - We NEVER directly modify a state variable.
React doesn`t direct this change. Only use the 'Setter' function. - We can name the state variable anything we wish.
- We can track any kind of data that changes over time - a number, string, array of objects, etc
- When a component is rerendered, all of its children get rerendered too.
- A state variable can be passed to a child component!
At that point, the state variable is now being used as props.
Reducer = Function that manages changes to an object
리듀서는 머리로는 알겠는데 딱히 설명이 안되네..
암튼 useState -> useReducer를 쓰고 state 처리를 위한 Reducer Function을 type과 payload 를 바탕으로 작성
- We are using function-based state in a functional component.