React.js – CMARIX QandA https://www.cmarix.com/qanda Fri, 30 May 2025 06:27:54 +0000 en-US hourly 1 https://wordpress.org/?v=6.9 How do you Handle Race Conditions in API Calls? https://www.cmarix.com/qanda/how-do-you-handle-race-conditions-in-api-calls/ https://www.cmarix.com/qanda/how-do-you-handle-race-conditions-in-api-calls/#respond Thu, 22 May 2025 12:31:56 +0000 https://www.cmarix.com/qanda/?p=1272 Race conditions can occur when multiple API calls are made in quick succession. One such instance can be, when a user types rapidly into a search field. If earlier requests return after newer ones, outdated data can overwrite the latest results. We can prevent this by using the AbortController API to cancel in-flight requests before […]

The post How do you Handle Race Conditions in API Calls? appeared first on CMARIX QandA.

]]>
Race conditions can occur when multiple API calls are made in quick succession. One such instance can be, when a user types rapidly into a search field. If earlier requests return after newer ones, outdated data can overwrite the latest results. We can prevent this by using the AbortController API to cancel in-flight requests before starting a new one. This ensures only the most relevant response updates the state.

 useEffect(() => {
  const controller = new AbortController();
  const fetchData = async () => {
    try {
      const response = await fetch(`/api/data?query=${query}`, {
        signal: controller.signal,
      });
      const result = await response.json();
      setData(result);
    } catch (err) {
      if (err.name !== 'AbortError') {
        console.error('API Error:', err);
      }
    }
  };
  fetchData();
  return () => {
    controller.abort(); // Cancels the previous request
  };
}, [query]);

The post How do you Handle Race Conditions in API Calls? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-do-you-handle-race-conditions-in-api-calls/feed/ 0
What is the Context API pitfall and how do you avoid it? https://www.cmarix.com/qanda/context-api-pitfall-in-react/ https://www.cmarix.com/qanda/context-api-pitfall-in-react/#respond Thu, 22 May 2025 12:14:14 +0000 https://www.cmarix.com/qanda/?p=1263 The main pitfall is that all components consuming a context via , even if the specific data they use hasn’t changed. This happens because the provider usually passes a new object reference on each render. What are the Avoidance Strategies of Context API pitfall? Split Contexts: Create smaller, more focused contexts instead of one large […]

The post What is the Context API pitfall and how do you avoid it? appeared first on CMARIX QandA.

]]>
The main pitfall is that all components consuming a context via , even if the specific data they use hasn’t changed. This happens because the provider usually passes a new object reference on each render.

What are the Avoidance Strategies of Context API pitfall?

Split Contexts: Create smaller, more focused contexts instead of one large global context. Components subscribe only to the context they need.

Memoize the Context Value:

Wrap the value object passed to the Provider in useMemo (and memoize functions within it using useCallback) so its reference only changes when its actual contents change.

Use Libraries with Selectors:

State management libraries (Zustand, Jotai) or use-context-selector allow components to subscribe only to specific slices of the context state.

Problem: Every consuming component re-renders when any value in context changes.

Fix:

  • Split contexts (AuthContext, ThemeContext)
  • Use memoization:

Example:

// AuthProvider.js
const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const logout = () => { /* logout logic */ };
  const value = useMemo(() => ({ user, logout }), [user]);
  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

The post What is the Context API pitfall and how do you avoid it? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/context-api-pitfall-in-react/feed/ 0
How Do You Optimize Large React App? https://www.cmarix.com/qanda/how-do-you-optimize-large-react-app/ https://www.cmarix.com/qanda/how-do-you-optimize-large-react-app/#respond Thu, 22 May 2025 12:07:18 +0000 https://www.cmarix.com/qanda/?p=1256 Optimization involves reducing bundle size, improving runtime speed, and enhancing perceived performance. Key strategies: Simplified Example (React.memo):

The post How Do You Optimize Large React App? appeared first on CMARIX QandA.

]]>
Optimization involves reducing bundle size, improving runtime speed, and enhancing perceived performance. Key strategies:

  • Code Splitting: Load code on demand (route-based or component-based) using React.lazy and Suspense.
  • Memoization: Prevent unnecessary re-renders using React.memo, useMemo, useCallback.
  • Bundle Analysis: Use tools (webpack-bundle-analyzer) to find large dependencies.
  • Tree Shaking: Ensure unused code is removed by the bundler.
  • Virtualization: Render only visible items in long lists/tables (react-window).
  • Optimize Context: Split contexts, memoize values to avoid excessive re-renders.
  • SSR/SSG: Improve initial load time with server-side rendering or static generation.
  • Profiling: Use React DevTools Profiler to find bottlenecks.

Simplified Example (React.memo):

import React from 'react';
// Assume UserProfile makes an expensive calculation or renders complex UI
function UserProfile({ user }) {
  console.log(`Rendering profile for ${user.name}`);
  // ... complex rendering ...
  return <div>{user.name}</div>;
}
// Memoize the component: It will only re-render if the 'user' prop changes reference or value.
const MemoizedUserProfile = React.memo(UserProfile);
// Usage: <MemoizedUserProfile user={currentUser} />

The post How Do You Optimize Large React App? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-do-you-optimize-large-react-app/feed/ 0
What are CSS Modules in React? https://www.cmarix.com/qanda/css-modules-in-react/ https://www.cmarix.com/qanda/css-modules-in-react/#respond Thu, 22 May 2025 12:01:55 +0000 https://www.cmarix.com/qanda/?p=1249 CSS Modules are CSS files where class names and animation names are locally scoped by default. Name these files as style.module.css for enabling this. After importing these files into a React component, an object is returned, which maps your original class names to unique, generated class names. This prevents global CSS conflicts between components.

The post What are CSS Modules in React? appeared first on CMARIX QandA.

]]>
CSS Modules are CSS files where class names and animation names are locally scoped by default. Name these files as style.module.css for enabling this. After importing these files into a React component, an object is returned, which maps your original class names to unique, generated class names. This prevents global CSS conflicts between components.

/* styles.module.css */
.button {
  background-color: red;
}
import styles from './styles.module.css';
<button className={styles.button}>Click</button>

The post What are CSS Modules in React? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/css-modules-in-react/feed/ 0
Explain Error Boundary and How to Create One https://www.cmarix.com/qanda/explain-error-boundary-and-how-to-create-one/ https://www.cmarix.com/qanda/explain-error-boundary-and-how-to-create-one/#respond Thu, 22 May 2025 11:57:20 +0000 https://www.cmarix.com/qanda/?p=1242 Error Boundaries are React components (currently must be class components) that catch JavaScript errors during rendering, in lifecycle methods, and in constructors of their child component tree. They prevent the entire app from crashing due to an error in one part and allow displaying a fallback UI. They use static getDerivedStateFromError() to update state and […]

The post Explain Error Boundary and How to Create One appeared first on CMARIX QandA.

]]>
Error Boundaries are React components (currently must be class components) that catch JavaScript errors during rendering, in lifecycle methods, and in constructors of their child component tree. They prevent the entire app from crashing due to an error in one part and allow displaying a fallback UI.

They use static getDerivedStateFromError() to update state and trigger a fallback UI render, and componentDidCatch() for side effects like logging errors. They do not catch errors in event handlers, async code, SSR, or themselves.

Simplified Example (Class Component):

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error, info) {
    console.error("ErrorBoundary caught:", error, info);
  }
  render() {
    return this.state.hasError ? <h2>Something went wrong.</h2> : this.props.children;
  }
}


// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

The post Explain Error Boundary and How to Create One appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/explain-error-boundary-and-how-to-create-one/feed/ 0
How would You Persist Specific Redux Slices to localStorage? https://www.cmarix.com/qanda/persist-specific-redux-slices-to-localstorage/ https://www.cmarix.com/qanda/persist-specific-redux-slices-to-localstorage/#respond Thu, 22 May 2025 11:49:21 +0000 https://www.cmarix.com/qanda/?p=1235 Use the redux-persist library. It automates saving and rehydrating parts of your Redux store to/from storage (like localStorage). Manually subscribing to the store and using localStorage.setItem/getItem is complex and error-prone.  What are the Features of Persist specific Redux Slices to localStorage? Simplified Example (redux-persist Config):

The post How would You Persist Specific Redux Slices to localStorage? appeared first on CMARIX QandA.

]]>
Use the redux-persist library. It automates saving and rehydrating parts of your Redux store to/from storage (like localStorage). Manually subscribing to the store and using localStorage.setItem/getItem is complex and error-prone.

 What are the Features of Persist specific Redux Slices to localStorage?

  • Handles serialization/deserialization.
  • Supports various storage engines.
  • Allows whitelisting/blacklisting specific slices.
  • Provides transforms and migrations.

Simplified Example (redux-persist Config):

import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // localStorage
import rootReducer from './reducers'; // Your combined reducers
const persistConfig = {
  key: 'root',        // Key in localStorage
  storage,            // Storage engine
  whitelist: ['auth', 'cart'] // ONLY persist these slices
  // blacklist: ['tempData'] // OR persist everything EXCEPT these
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
// Configure store with persisted reducer
const store = configureStore({
  reducer: persistedReducer,
  // Middleware setup needed to ignore redux-persist actions
});
const persistor = persistStore(store);
// Wrap app in <PersistGate loading={null} persistor={persistor}> in index.js

The post How would You Persist Specific Redux Slices to localStorage? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/persist-specific-redux-slices-to-localstorage/feed/ 0
How Would You Handle Dependent API Calls in Redux? https://www.cmarix.com/qanda/how-would-you-handle-dependent-api-calls-in-redux/ https://www.cmarix.com/qanda/how-would-you-handle-dependent-api-calls-in-redux/#respond Thu, 22 May 2025 11:37:01 +0000 https://www.cmarix.com/qanda/?p=1227 Manage asynchronous workflows where one call depends on another’s result. Modern Redux Toolkit (RTK) Approaches: Use createAsyncThunk chaining:

The post How Would You Handle Dependent API Calls in Redux? appeared first on CMARIX QandA.

]]>
Manage asynchronous workflows where one call depends on another’s result.

Modern Redux Toolkit (RTK) Approaches:

  1. Chain  Dispatch a second thunk from within the first thunk’s payloadCreator after the first API call succeeds. Good for linear dependencies.
  2. RTK Query: Define endpoints using createApi. Use query hooks in components. The second query hook can use the skip option to wait until data from the first query (e.g., a user ID) is available. Often the cleanest approach for API data fetching.

Use createAsyncThunk chaining:

export const fetchUserAndOrders = createAsyncThunk(
  'user/fetchUserAndOrders',
  async (userId, { dispatch }) => {
    const user = await fetch(`/api/users/${userId}`).then(res => res.json());
    await dispatch(fetchOrders(user.id));
    return user;
  }
);

The post How Would You Handle Dependent API Calls in Redux? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-would-you-handle-dependent-api-calls-in-redux/feed/ 0
How Do you Optimize a Huge Data Table in React? https://www.cmarix.com/qanda/how-do-you-optimize-a-huge-data-table-in-react/ https://www.cmarix.com/qanda/how-do-you-optimize-a-huge-data-table-in-react/#respond Thu, 22 May 2025 11:31:06 +0000 https://www.cmarix.com/qanda/?p=1221 The primary technique is Windowing / Virtualization. Only render the rows (and sometimes columns) currently visible in the viewport, drastically reducing the number of DOM nodes. Few Key Techniques a Huge Data Table in React: Server-Side Operations: For truly massive datasets, fetch data in pages/chunks (pagination/infinite scroll) instead of loading all data client-side. Simplified Example: […]

The post How Do you Optimize a Huge Data Table in React? appeared first on CMARIX QandA.

]]>
The primary technique is Windowing / Virtualization. Only render the rows (and sometimes columns) currently visible in the viewport, drastically reducing the number of DOM nodes.

Few Key Techniques a Huge Data Table in React:

  1. Virtualization: Use libraries like react-window, react-virtualized, or @tanstack/react-virtual.
  2. Memoization: Use React.memo on row components to prevent re-renders if props haven’t changed.
  3. Debounce/Throttle: For filtering/sorting inputs.

Server-Side Operations: For truly massive datasets, fetch data in pages/chunks (pagination/infinite scroll) instead of loading all data client-side.

Simplified Example: react-window

import { FixedSizeList as List } from 'react-window';

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

<List height={500} itemCount={10000} itemSize={35} width={300}>
  {Row}
</List>

Other Tips:

  • Debounce filters
  • Use React.memo
  • Avoid unnecessary re-renders

The post How Do you Optimize a Huge Data Table in React? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/how-do-you-optimize-a-huge-data-table-in-react/feed/ 0
Explain the Fiber Architecture and How it Improves React’s Rendering Process? https://www.cmarix.com/qanda/fiber-architecture-react/ https://www.cmarix.com/qanda/fiber-architecture-react/#respond Thu, 22 May 2025 10:50:55 +0000 https://www.cmarix.com/qanda/?p=1212 Fiber is React’s core reconciliation algorithm (since React 16), replacing the old synchronous stack reconciler. It represents work as units called “Fibers”. Fiber enables React to: Break work into chunks: Rendering isn’t one monolithic task.

The post Explain the Fiber Architecture and How it Improves React’s Rendering Process? appeared first on CMARIX QandA.

]]>
Fiber is React’s core reconciliation algorithm (since React 16), replacing the old synchronous stack reconciler. It represents work as units called “Fibers”. Fiber enables React to:

Break work into chunks: Rendering isn’t one monolithic task.

  • Prioritize updates: High-priority work (like user input) can interrupt low-priority work (like rendering offscreen elements).
  • Pause, resume, or abort work: Makes rendering flexible and non-blocking.
  • This results in a smoother, more responsive UI, especially during complex updates, and enables concurrent features.
  • Simplified Example (Conceptual Benefit):
  • Fiber allows React to handle a user typing into an input field immediately, even if a large list is currently trying to re-render in the background due to a data update. The list rendering gets paused, the input is processed, and then the list rendering resumes.

The post Explain the Fiber Architecture and How it Improves React’s Rendering Process? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/fiber-architecture-react/feed/ 0
How Do You Handle Unauthorized Widget Components In The Dashboard Config? https://www.cmarix.com/qanda/unauthorized-widget-handling-react-dashboard-security/ https://www.cmarix.com/qanda/unauthorized-widget-handling-react-dashboard-security/#respond Wed, 21 May 2025 11:33:39 +0000 https://www.cmarix.com/qanda/?p=1205 Filter the components to be rendered based on the user’s permissions before the render cycle. True security relies on the backend only sending data/configuration the user is authorized for, but the frontend needs to display accordingly. Methods: Simplified Example (Filtering Config):

The post How Do You Handle Unauthorized Widget Components In The Dashboard Config? appeared first on CMARIX QandA.

]]>
Filter the components to be rendered based on the user’s permissions before the render cycle. True security relies on the backend only sending data/configuration the user is authorized for, but the frontend needs to display accordingly.

Methods:

  • Filter Configuration Array: Preferred for dynamic lists.
  • Conditional Rendering: Use && or ternary operators based on permission checks.
  • Higher-Order Component (HOC): Wrap components with a permission-checking HOC.

Simplified Example (Filtering Config):

// Assume:
// userPermissions = ['view_sales', 'edit_users'];
// allWidgets = [
//   { id: 'sales', component: Sales, permission: 'view_sales' },
//   { id: 'users', component: Users, permission: 'edit_users' },
//   { id: 'admin', component: Admin, permission: 'admin_only' },
// ];

const authorizedWidgets = allWidgets.filter(widget =>
  !widget.permission || userPermissions.includes(widget.permission)
);

// Then render:
// {authorizedWidgets.map(widget => <widget.component key={widget.id} />)}

The post How Do You Handle Unauthorized Widget Components In The Dashboard Config? appeared first on CMARIX QandA.

]]>
https://www.cmarix.com/qanda/unauthorized-widget-handling-react-dashboard-security/feed/ 0