- State Management in React -
++ State Management in React +
+ + ++ What is State Management ? +
+ + ++ + "State" is any data that describes the current behavior of an application. + + This could include values like "a list of objects fetched from the server", "which item is currently selected", "name of the currently logged-in user", and "is this modal open?". +
+ + ++ + State + + allows you to create interactive and dynamic user interfaces. By managing the state of component, you can update the UI in response to user interactions, API calls, or other events. +
+ + ++ Here are different types for state management that will be covered in our example: +
+ + +-
-
+
- + + Local State: + + : Data we manage in one or another component e.g handling inputs data in from. + +
- + + Server State : + + Data are fetched from the server via an API and cached on the client, there are a couple of great libraries that make data fetching in React a breeze such as: + + + React Query + + + . + -
+ Let's break down the state management code example ( + + view demo + + ): +
+ + + + + + + ++ Initializing local state for filters using useState hook +
+
+ Here, we use the
+
+ useState
+
+ hook to manage the local state of our filters. This state will store the user's input for the movie title and category.
+
+ Use React Query to Manage Server State +
+
+ The
+
+ fetchData
+
+ function builds the API URL with query parameters and fetches data from the server.
+
+ The
+
+ useQuery
+
+ hook from React Query fetches data based on the current filters and manages the server state, including loading and error states.
+
+ Error Handling +
++ If an error occurs during data fetching, we display an error message. +
++ Handle User Input: SearchField & Select +
+
+ We use the
+
+ SearchField
+
+ component to allow the user to input a search query. The
+
+ onChange
+
+ handler updates the local state with the new search term, which triggers a re-fetch of the data.
+
+ The
+
+ Select
+
+ component allows the user to choose a category. The
+
+ onChange
+
+ handler updates the local state with the selected category, which also triggers a re-fetch of the data.
+
+ Loading State +
++ While data is being fetched, we display a loading indicator. +
+
- Write some description here -
- - - +