CPRG-306 Week 7

Managing State


Agenda

  1. Tailwind Component Libraries
  2. Immutability
  3. State Batching
  4. 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


Other Component Libraries

Note: If you want to use one of these libraries, you should create a project that does NOT use Tailwind CSS.


Vercel's AI


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

  1. Create a Dog component, display name and age
  2. Create a DogList component, display a list of Dogs
  3. Create a DogForm component, allow user to add a new dog
  4. Create a Page component that displays the DogList and DogForm
  5. Consider adding a delete button to the Dog component