You can use useState to track any kind of data: strings, numbers, Booleans, arrays, objects. For example, you can track the number of times a cat has been petted with const [timesPetted, setTimesPetted] = useState(0)!
You might’ve noticed that although isHungry is a const, it is seemingly reassignable! What is happening is when a state-setting function like setIsHungry is called, its component will re-render. In this case the Cat function will run again—and this time, useState will give us the next value of isHungry.
While you can think of props as arguments you use to configure how components render, state is like a component’s personal data storage. State is useful for handling data that changes over time or that comes from user interaction. State gives your components memory!
Any component that renders other components is a parent component. Here, Cafe is the parent component and each Cat is a child component
think of curly braces as creating a portal into JS functionality in your JSX
Because JSX is included in the React library, it won’t work if you don’t have import React from 'react' at the top of your file!
As a general rule, use props to configure a component when it renders. Use state to keep track of any component data that you expect to change over time.
You can add state to a component by calling React’s useState Hook. A Hook is a kind of function that lets you “hook into” React features. For example, useState is a Hook that lets you add state to function components. You can learn more about other kinds of Hooks in the React documentation.
Then you declare the component’s state by calling useState inside its function. In this example, useState creates an isHungry state variable:
useState to track any kind of data: strings, numbers, Booleans, arrays, objects
Calling useState does two things: it creates a “state variable” with an initial value—in this case the state variable is isHungry and its initial value is true it creates a function to set that state variable’s value—setIsHungry
See the <> and </> above? These bits of JSX are fragments. Adjacent JSX elements must be wrapped in an enclosing tag. Fragments let you do that without nesting an extra, unnecessary wrapping element like View.
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.