CPRG-306 Week 7
Managing State
Agenda
- Tailwind Component Libraries
- Immutability
- State Batching
- Sharing State Between Components
Tailwind Component Libraries
- A component library is a collection of pre-built components
- Useful for building UIs quickly
- Some typical components include buttons, pop-up modals, form elements, even entire layouts and dashboards
Tailwind Component Libraries, cont'd
- Tailwind has a number of component libraries available
Other Component Libraries
- Material-UI (opens in a new tab)
- Ant Design (opens in a new tab)
- Chakra UI (opens in a new tab)
- React Bootstrap (opens in a new tab)
Note: If you want to use one of these libraries, you should create a project that does NOT use Tailwind CSS.
Vercel's AI
- v0.dev (opens in a new tab)
- Great for generating user interfaces quickly
Immutability
- State should be treated as immutable
- Never mutate state directly
- Always use
setState
to update state
Immutability Demo
Create a broken counter that increments by 1 that doesn't use setState
State Batching
- React batches state updates
- Multiple
setState
calls are batched together - React will only re-render once
set state
schedules a state update, it doesn't immediately update the state
State Batching Demo
Create a counter that increments by 1 using setState
multiple times
Solution to the broken counter
- Use a function to update state
- Pass the previous state to the function
setCount((prevCount) => prevCount + 1);
State Containing Objects
- When updating state that contains objects, you must create a new object
- You can use the spread operator to create a new object
const [person, setPerson] = useState({ name: "Mario", age: 30 });
setPerson({ ...person, age: 31 }); // copy the previous person object and update the age
// or
setPerson((prevPerson) => ({ ...prevPerson, age: 31 })); // use a function to update the state
State Containing Objects Demo
Create a person object with a name and age, and update the age
State Management
- React state is local to the component
- If you need to share state between components, you need to lift the state up to a common ancestor
- And pass the state down as props
- A common pattern is to use a state management library like Redux or Context API. (Beyond the scope of this course)
Lifting State Up Demo
- Create a Dog component, display name and age
- Create a DogList component, display a list of Dogs
- Create a DogForm component, allow user to add a new dog
- Create a Page component that displays the DogList and DogForm
- Consider adding a delete button to the Dog component