Week 5
Goals
- Get an intuition for how state dictates behavior in an app
- Ponder some examples/use cases for state
- Complete this week's challenge!
Understanding React State
What is State?
Remember our house analogy?
- HTML is the walls (structure)
- CSS is the paint (styling)
- TypeScript is the door (logic)
State is the furniture inside the house - it can change and move around dynamically!
State is data that can change over time in your React component. When state changes, React automatically re-renders the component to show the updated information.
In effect, this is what gives functionality and actual usefulness to your code.
Some Real-World Examples...
There are a few ways to think about state in everyday terms:
A light switch - It has two states: ON or OFF
- Current state: The light is currently ON
- Action: You flip the switch
- New state: The light is now OFF
A shopping cart - It has a list of items
- Current state: 3 items in cart
- Action: You add a new item
- New state: 4 items in cart
Our Kudos App - It will have a list of kudos cards
- Current state: 1 kudos card displayed
- Action: User submits the form
- New state: 2 kudos cards displayed
This is exactly what we're building today!
Hooks
Hooks are functions that let you "hook into" and control React states.
Since we can use hooks for each individual (functional) component, it is actually possible to write entire React applications using only functional components, which in turn HIGHLY simplifies the component model that we discussed last week.
Before we dive into how they are used in our project, let's go over some properties of hooks that will help you understand them better
General Properties
- They can only be used with functional components. You CANNOT use them in class components.
- Every time our function runs/is called, its hooks must run in the exact same order. In other words, we cant really have a hook inside of a conditional statement, since if the statement didn't run, we would have an error. This follows that we really can't have hooks nested inside of anything (loops, conditionals, functions, etc.). They must be at the top level of our function, and always called in the exact same order.
- Lastly, there are a few important types of hooks that React allows us to use. In the next section, I will go over one of these types.
The useState Hook
React gives us a special function called useState to manage state. The pattern looks like this:
const [currentValue, functionToUpdateIt] = useState(initialValue);
Think of it like this:
- currentValue - What the state is right now
- functionToUpdateIt - How to change it
- initialValue - What it starts as
Don't worry if this seems abstract - it'll make perfect sense once we start building!