Unit 5: Client-Server Communication and Routing - Subjective Questions
INT252 — Web App Development With Reactjs • Practice Questions with Detailed Answers
20 questions
Define HTTP and explain the structure of an HTTP request and an HTTP response.
HTTP (Hypertext Transfer Protocol) is an application-layer protocol used for communication between clients and servers on the web. It follows a request-response model.
An HTTP request contains:
- Method: Specifies the action, such as
GET,POST,PUT,PATCH, orDELETE. - URL: Identifies the requested resource.
- Headers: Carry metadata such as content type and authorization credentials.
- Body: Contains data sent to the server, generally in
POST,PUT, andPATCHrequests.
An HTTP response contains:
- Status code: Indicates the result, such as
200for success,404for not found, or500for a server error. - Headers: Describe the response format, caching rules, and other metadata.
- Body: Contains the returned resource or an error description.
HTTP is generally stateless, meaning each request must contain the information required for the server to process it.
Explain REST principles and describe how common HTTP methods are used in a RESTful API.
REST (Representational State Transfer) is an architectural style for designing network APIs around resources.
Major REST principles include:
- Client-server separation: User-interface concerns are separated from data-storage concerns.
- Statelessness: Each request contains all information needed for processing.
- Uniform interface: Resources are accessed consistently through URLs and standard HTTP methods.
- Resource orientation: Entities such as users or products are represented as resources.
- Cacheability: Responses specify whether they may be cached.
- Layered system: Clients need not know whether they are communicating directly with the main server or through an intermediary.
Common HTTP methods:
GET /productsretrieves products.POST /productscreates a product.PUT /products/5completely replaces product 5.PATCH /products/5partially updates product 5.DELETE /products/5removes product 5.
A RESTful API also uses meaningful status codes, such as 201 Created, 400 Bad Request, and 404 Not Found.
Describe how the Fetch API can be used to retrieve JSON data in a React application. How should HTTP and network errors be handled?
The Fetch API provides the browser's built-in fetch() function for making HTTP requests. It returns a promise that resolves to a Response object.
A typical process is:
- Call
fetch()with the resource URL. - Check the response's
okproperty. - Throw an error for an unsuccessful HTTP status.
- Parse the body using
response.json(). - Store or return the resulting data.
- Handle failures with
catchortry...catch.
Example:
async function loadUsers() {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error(Request failed: ${response.status});
}
return response.json();
}
fetch() rejects automatically for failures such as a network connection error, but it normally does not reject for HTTP errors such as 404 or 500. Therefore, checking response.ok or response.status is essential.
Explain common Axios usage patterns for GET, POST, and authenticated requests. Mention how Axios handles responses and errors.
Axios is a promise-based HTTP client that can be used in browsers and other JavaScript environments.
Common patterns include:
- Retrieve data with
axios.get("/api/items"). - Create data with
axios.post("/api/items", newItem). - Pass query parameters through the
paramsconfiguration property. - Send authentication credentials through the
headersproperty. - Create a reusable Axios instance with a base URL, default headers, and interceptors.
Axios places parsed response data in response.data. Unlike Fetch, Axios normally rejects the promise when the server returns an unsuccessful HTTP status.
In an error handler:
error.responseindicates that the server responded with an error status.error.requestindicates that a request was sent but no response was received.error.messagedescribes setup or other errors.
Interceptors can centrally attach access tokens, log requests, transform responses, or react to authorization failures.
Compare the Fetch API and Axios for client-server communication in React applications.
Fetch and Axios similarities:
- Both support promise-based HTTP communication.
- Both can send headers, request bodies, and query parameters.
- Both work with
asyncandawait.
Key differences:
- Availability: Fetch is built into modern browsers, while Axios is an external dependency.
- JSON handling: Fetch requires an explicit call such as
response.json(); Axios generally parses JSON automatically. - HTTP errors: Fetch requires a manual
response.okcheck; Axios rejects unsuccessful HTTP status responses by default. - Interceptors: Axios provides built-in request and response interceptors.
- Configuration: Axios instances make reusable base URLs, headers, and policies convenient.
- Cancellation: Both can support cancellation, commonly through
AbortControllerin modern usage.
Fetch is suitable when a lightweight built-in API is enough. Axios can be preferable when an application benefits from centralized configuration, automatic transformations, or interceptors.
Describe how a React interface should handle loading, error, success, and empty states during data fetching.
A data-driven interface should represent every meaningful request state explicitly.
- Loading state: Display a progress indicator, skeleton, or other placeholder while the initial request is pending.
- Error state: Show a clear error message and, when appropriate, a retry action.
- Empty state: If the request succeeds but returns no records, explain that no data is available and offer a relevant next action.
- Success state: Render the returned data.
- Background refresh state: Keep existing data visible while showing a subtle updating indicator.
The states should be checked in a logical order. For example, the component may first handle initial loading, then errors, then an empty collection, and finally populated content.
An empty result is not the same as an error: it is a successful response with no matching content. Similarly, background fetching should usually not replace usable cached data with a full-screen loader.
Explain how useEffect can be used for data fetching. Include the purpose of its dependency array and cleanup function.
useEffect runs side effects after React commits a render. A component can use it to request data whenever a relevant value, such as a user ID, changes.
Typical steps are:
- Start the request inside the effect.
- Update loading, data, and error state as the request progresses.
- List every reactive value used by the effect in its dependency array.
- Return a cleanup function when the active work must be cancelled or disconnected.
An empty dependency array causes the effect to run after the initial mount. A dependency such as [userId] causes it to run after mounting and whenever userId changes.
For network requests, cleanup can call AbortController.abort(). This prevents obsolete requests from continuing unnecessarily and helps avoid race conditions where an older response overwrites newer data.
The effect callback itself should not be declared async, because an effect must return either a cleanup function or nothing. An inner asynchronous function can be defined and invoked instead.
Distinguish between client state and server state in a React application, with suitable examples.
Client state is owned and controlled primarily by the frontend application.
Examples include:
- Whether a modal is open
- The selected tab
- Unsaved form input
- Theme or display preferences
- Temporary filter controls
Server state originates from a remote system and is only a local snapshot of authoritative data.
Examples include:
- A product catalog
- User account details
- Order history
- Comments loaded from an API
- Inventory availability
Server state introduces concerns that ordinary client state may not have, including:
- Asynchronous loading and failures
- Caching and invalidation
- Data becoming stale
- Multiple components requesting the same resource
- Background refetching
- Concurrent updates by other users
useState or a client-state store is suitable for local interface state. A server-state library such as React Query is better suited to remote data lifecycle management.
Discuss the limitations of using useEffect and useState as the primary mechanism for synchronizing server data.
Although useEffect and useState can fetch data, a manual implementation becomes difficult as an application grows.
Important limitations include:
- Repeated loading, error, and data state logic across components
- No automatic shared cache or request deduplication
- Manual handling of stale data and invalidation
- Race conditions when parameters change quickly
- Additional work for retries and cancellation
- Difficulty keeping multiple views synchronized after a mutation
- No built-in background refetching on focus or reconnection
- Risk of dependency-array mistakes and unnecessary requests
- Development behavior such as Strict Mode exposing effects that are not safely repeatable
useEffect is still appropriate for synchronizing React with external systems, such as subscriptions or browser APIs. However, server data has a specialized lifecycle. React Query and similar libraries encode that lifecycle directly, reducing manual coordination and improving consistency.
Introduce React Query and explain the roles of QueryClient, QueryClientProvider, query keys, and query functions.
React Query, also known as TanStack Query, manages asynchronous server state in frontend applications.
Its main elements are:
QueryClient: Owns the query cache and coordinates query behavior.QueryClientProvider: Makes the client and its cache available to descendant components.- Query key: A serializable identifier for cached data, such as
["users", userId]. - Query function: An asynchronous function that retrieves data or throws an error.
useQuery: Subscribes a component to a query and provides data and request-state information.
Query keys should include every parameter used by the query function. For example, different user IDs require different keys so their results are cached separately.
React Query can provide caching, request deduplication, retries, stale-data management, background refetching, and invalidation. It does not replace the API; it coordinates when API functions run and how their results are shared.
Explain caching, freshness, invalidation, and background synchronization in React Query.
React Query stores successful query results in a cache under their query keys.
- Fresh data: Data is considered recent enough that React Query can reuse it without immediately refetching.
- Stale data: Data may still be displayed, but it is eligible for a background refresh.
staleTime: Controls how long cached data remains fresh.- Garbage-collection time: Controls how long an unused query stays in memory before removal.
- Invalidation: Marks matching cached queries as stale, commonly after a mutation changes related server data.
- Background synchronization: Refetches data while retaining the cached result on screen.
Depending on configuration, stale queries may refetch when a component mounts, the browser window regains focus, or the network reconnects. This produces a responsive interface because cached data can appear immediately while newer data is requested.
Caching must balance responsiveness and correctness. Frequently changing data may need a short staleTime, while relatively stable reference data can remain fresh longer.
Define client-side routing and explain how it differs from traditional server-side page navigation.
Client-side routing maps browser URLs to React views without requesting a completely new HTML document for every navigation.
When a user follows an internal route:
- The router updates the browser history.
- It matches the new URL against route definitions.
- React renders the corresponding component tree.
- Shared application state and layouts can remain mounted.
In traditional server-side navigation, each link usually causes the browser to request a new document and reload the page. Client-side routing generally makes transitions faster because the JavaScript application is already loaded.
However, the server must still be configured to return the application's entry document for valid client routes requested directly. The application should also provide a not-found route and use standard URLs so browser history, bookmarks, refreshes, and deep links behave correctly.
Describe the basic routing configuration required to set up React Router in a React application.
A typical React Router setup requires the following:
- Install the router package.
- Place a router provider near the application root, such as
BrowserRouter, or use a configured data router withRouterProvider. - Define route patterns and associate them with React elements.
- Add a fallback route for unmatched URLs.
A conceptual route hierarchy might include:
/for the home view/productsfor a product list/products/:productIdfor product details/accountfor a user account*for a not-found view
BrowserRouter uses the browser History API, producing normal-looking URLs. In a production deployment, the web server must support history fallback so that a direct request to a client-managed path returns the application entry document rather than an unintended server 404 response.
Explain declarative and programmatic navigation in React Router. When should each approach be used?
Declarative navigation uses components such as Link and NavLink.
Linkcreates an internal navigation link without causing a full page reload.NavLinkadditionally exposes whether its destination is active, which is useful for menus and tabs.- Declarative links are preferable when navigation is directly initiated by choosing a visible destination.
Programmatic navigation uses a navigation function, commonly obtained from useNavigate.
It is appropriate when navigation occurs as the result of logic, such as:
- Redirecting after successful form submission
- Returning to a previous route
- Moving to a login page after session expiration
- Replacing a temporary route in browser history
Internal application routes should generally use router links instead of plain anchor navigation because a normal <a> element can reload the entire document. Programmatic navigation should represent a genuine workflow transition, not replace accessible links unnecessarily.
What are dynamic routes? Explain how route parameters are declared, read, and used to fetch resource-specific data.
A dynamic route contains a variable segment that can match different URL values. For example, /products/:productId matches /products/12 and /products/85.
:productIddeclares a route parameter.- A component can read it using a router hook such as
useParams. - Route parameter values are normally strings and should be validated or converted when required.
- The parameter can be supplied to an API function to retrieve the corresponding resource.
For React Query, the parameter should also be included in the query key, for example ["product", productId]. This ensures that each product has a separate cache entry.
The component should handle missing or invalid identifiers and a legitimate 404 Not Found response. Route parameters identify a resource as part of the path, whereas optional view controls such as sorting are usually represented by query parameters.
Describe how query parameters are read and updated in a React application. How do they differ from route parameters?
Query parameters appear after ? in a URL, such as /products?category=books&page=2.
A router API such as useSearchParams can be used to:
- Read values such as
categoryandpage - Add or update filters
- Remove parameters
- Trigger navigation to the resulting URL
Query parameter values are strings, so numbers and Boolean values require parsing and validation. Defaults should be applied when parameters are absent or invalid.
Difference from route parameters:
- Route parameters are part of the path, such as
/products/:productId, and commonly identify a particular resource. - Query parameters are optional key-value pairs commonly used for filtering, sorting, searching, pagination, or display options.
Keeping important view state in the URL makes the view bookmarkable, shareable, and compatible with browser back and forward navigation.
Explain nested routes and layout routes in React Router. What is the purpose of an outlet?
Nested routes represent a hierarchy in which child routes render within a parent route. They are useful when related pages share structure or URL segments.
For example, an /account parent route may contain children for:
/account/profile/account/security/account/orders
A layout route provides shared interface elements such as a header, navigation menu, sidebar, or footer. The layout remains visible while the matched child content changes.
An outlet is the placeholder in the parent element where the matched child route is rendered. Without an outlet, the parent may match successfully, but its child element will have no designated rendering location.
Nested routes reduce repeated layout code and make the route hierarchy correspond to the visual hierarchy. An index route can define the default child rendered when the parent path is matched without an additional child segment.
Design and explain a protected-route strategy for an authenticated React application.
A protected route restricts a client-side view based on authentication or authorization state.
A suitable strategy includes:
- Determine whether authentication is still loading.
- Show a temporary loading state while the session is being verified.
- Render the protected child or outlet when the user is authorized.
- Redirect unauthenticated users to the login route.
- Preserve the intended destination so the user can return after signing in.
- Render a forbidden view when the user is authenticated but lacks the required role or permission.
Navigation history may be replaced during the redirect so the browser's Back button does not repeatedly return to the blocked route.
Client-side protection improves user experience but is not a security boundary. The server must independently authenticate every protected API request and enforce authorization rules. Hiding a route or button in React does not prevent direct requests to the backend.
Explain route-based code splitting and describe how lazy loading and a fallback interface improve application performance.
Route-based code splitting divides an application's JavaScript into separate bundles associated with different routes. Code for a route is loaded when that route is required rather than being included entirely in the initial bundle.
A common approach uses a dynamic import with React.lazy, while Suspense displays fallback content until the route module loads.
Benefits include:
- A smaller initial JavaScript download
- Faster parsing and execution
- Quicker initial rendering on slower devices or networks
- Deferred loading of infrequently visited features
The fallback should have stable dimensions and communicate that the destination is loading without causing disruptive layout movement. Route chunks may also be prefetched when user behavior indicates that navigation is likely.
Code-splitting boundaries should be reasonably coarse. Splitting every tiny component can create excessive requests and management overhead, whereas route-level boundaries often align naturally with user navigation.
Describe an end-to-end architecture for a routed React application that retrieves server data, caches it, handles mutations, and keeps the URL synchronized with the current view.
An end-to-end design can combine routing, API functions, and React Query as follows:
- Configure application routes, shared layouts, dynamic segments, and a not-found view.
- Store shareable controls such as search terms, filters, sorting, and pagination in query parameters.
- Read route and query parameters in the matched page component.
- Pass those values to a dedicated API function.
- Use a React Query key that includes every value affecting the request.
- Render initial loading, error, empty, and success states.
- Keep cached data visible during background refetching when appropriate.
- Use a mutation for create, update, or delete operations.
- After a successful mutation, update or invalidate related cached queries.
- Protect private route branches and enforce the same permissions on the server.
- Lazy-load large route modules to reduce the initial bundle.
This architecture separates responsibilities: the router manages location, API functions manage HTTP details, React Query manages server-state synchronization, and local React state manages temporary interface behavior. It also supports deep links, browser navigation, caching, retries, and consistent refresh behavior.
Define HTTP and explain the structure of an HTTP request and an HTTP response.
HTTP (Hypertext Transfer Protocol) is an application-layer protocol used for communication between clients and servers on the web. It follows a request-response model.
An HTTP request contains:
- Method: Specifies the action, such as
GET,POST,PUT,PATCH, orDELETE. - URL: Identifies the requested resource.
- Headers: Carry metadata such as content type and authorization credentials.
- Body: Contains data sent to the server, generally in
POST,PUT, andPATCHrequests.
An HTTP response contains:
- Status code: Indicates the result, such as
200for success,404for not found, or500for a server error. - Headers: Describe the response format, caching rules, and other metadata.
- Body: Contains the returned resource or an error description.
HTTP is generally stateless, meaning each request must contain the information required for the server to process it.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →