This is the third installment of a seven-part series designed to improve your React development skills. This project focuses on various methods for managing state in React applications.
Follow these instructions to get the application running:
- Install Node.js version 14.21.3:
nvm install v14.21.3
nvm use v14.21.3
- Install necessary packages:
npm install
- Start the application:
npm start
When building a React app using hooks, you can manage state:
- Locally:
useState()
- Between parent and child:
props
- Globally:
useContext()
- With REST APIs:
useQuery()
,usePaginatedQuery()
GOAL: Try to keep state management as simple as possible
-
Local State: Use the
useState()
hook locally within functional components. -
Lifting State: This is the process of moving local state up one level in the hierarchy to share state and its setter function as props.
-
Global State (with Contexts): Use this when you have multiple levels and refactoring becomes complex. Be aware that changing the state with
useContext()
can cause all components that use that context to re-render. -
Consider memoizing components to prevent unnecessary re-renders.
Once you use global state, you might consider other libraries like MobX, Redux, Overmind, Zustand, or Recoil, or simply stick with useState()
.
Managing external data states (loading, errors, data updates, and caching) can be complex. Some libraries that simplify this are:
- React Query, SWR (for REST APIs)
- Apollo Client, Urql (for GraphQL)
React Query provides tools for managing state with asynchronous data from REST APIs or GraphQL. It helps by:
- Caching data after the initial fetch, improving speed and user experience.
- Re-fetching data in the background to keep the site up-to-date.
- Providing information about the request, such as status or errors.
This project is part of a comprehensive React learning series: