Class Twenty-two Notes (401)
useState()
Hook
Thinking in React
Five Steps of thinking in React:
- Break the UI into a component hierarchy by applying the single responsibility principle, where one component should do one thing only.
- Build a static version in React by first building a bare-bone model without adding any interactivity
- Find the minial nut complete representation of UI state. In this step, what should be held as a state and what needs to be passed around as props should be decided
- Identify where the state should live. Since React has a hiereical flow, the state should be helod on the cloest parent components possible between siblings
- Add inverse data flow
State: A Component’s Memory
- A local variable isn’t sufficient when multiple components are triggered by the same event, and local variables not only do not persist between renders, but also they don’t trigger renders.
useState
hook allows the use of a state variable to regain the data between renders, and a state setter fnction allows updating variable and trigger React to render the component again
- Component A can access states in component B by adding the
useState
hook, and the state should be stored in their closest shared parent
Back to main page
References