FrontendDeveloper.in

React Interview Questions

  • Question 106

    What is flux?

    Flux is an application architecture (not a framework or library) designed by Facebook to manage data flow in React applications. It was created as an alternative to the traditional MVC (Model-View-Controller) pattern, and it emphasizes a unidirectional data flow to make state changes more predictable and easier to debug.

    Flux complements React by organizing the way data moves through your application, especially in large-scale or complex projects.

    Core Concepts of Flux

    Flux operates using four key components, each with a specific responsibility:

    • Actions
    • Plain JavaScript objects or functions that describe what happened (e.g., user interactions or API responses).
    • Example: { type: 'ADD_TODO', payload: 'Buy milk' }
    • Dispatcher
    • A central hub that receives actions and dispatches them to the appropriate stores.
    • There is only one dispatcher in a Flux application.
    • Stores
    • Hold the application state and business logic.
    • Respond to actions from the dispatcher and update themselves accordingly.
    • They emit change events that views can listen to.
    • Views (React Components)
    • Subscribe to stores and re-render when the data changes.
    • They can also trigger new actions (e.g., on user input).

    The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:

    flux

  • Question 107

    What is Redux?

    Redux is a predictable state container for JavaScript applications, most commonly used with React. It helps you manage and centralize your application’s state in a single source of truth, enabling easier debugging, testing, and maintenance—especially in large or complex applications. Redux core is tiny library(about 2.5kB gzipped) and has no dependencies.

  • Question 108

    What are the core principles of Redux?

    Redux follows three fundamental principles:

    1. Single source of truth: The state of your whole application is stored in an object tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
    const store = createStore(reducer);
    
    1. State is read-only: The only way to change the state is to emit an action, an object describing what happened. This ensures that neither the views nor the network callbacks will ever write directly to the state.
    const action = { type: 'INCREMENT' };
    store.dispatch(action);
    
    1. Changes are made with pure functions(Reducers): To specify how the state tree is transformed by actions, you write reducers. Reducers are just pure functions that take the previous state and an action as parameters, and return the next state.
    function counter(state = 0, action) {
    switch (action.type) {
    case 'INCREMENT':
    return state + 1;
    case 'DECREMENT':
    return state - 1;
    default:
    return state;
    }
    }
    
  • Question 109

    What are the downsides of Redux compared to Flux?

    While Redux offers a powerful and predictable state management solution, it comes with a few trade-offs when compared to Flux. These include:

    1. Immutability is essential Redux enforces a strict immutability model for state updates, which differs from Flux’s more relaxed approach. This means you must avoid mutating state directly. Many Redux-related libraries assume immutability, so your team must be disciplined in writing pure update logic. You can use tools like redux-immutable-state-invariant, Immer, or Immutable.js to help enforce this practice, especially during development.
    2. Careful selection of complementary packages Redux is more minimal by design and provides extension points such as middleware and store enhancers. This has led to a large ecosystem, but it also means you must thoughtfully choose and configure additional packages for features like undo/redo, persistence, or form handling—something Flux explicitly leaves out but may be simpler to manage in smaller setups.
    3. Limited static type integration While Flux has mature support for static type checking with tools like Flow, Redux’s type integration is less seamless. Although TypeScript is commonly used with Redux now, early Flow support was limited, and more boilerplate was required for static type safety. This may affect teams that rely heavily on type systems for large codebases.
  • Question 110

    What is the difference between `mapStateToProps()` and `mapDispatchToProps()`?

    mapStateToProps() is a utility which helps your component get updated state (which is updated by some other components):

    const mapStateToProps = (state) => {
    return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter),
    };
    };
    

    mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state):

    const mapDispatchToProps = (dispatch) => {
    return {
    onTodoClick: (id) => {
    dispatch(toggleTodo(id));
    },
    };
    };
    

    It is recommended to always use the “object shorthand” form for the mapDispatchToProps.

    Redux wraps it in another function that looks like (…args) => dispatch(onTodoClick(…args)), and pass that wrapper function as a prop to your component.

    const mapDispatchToProps = {
    onTodoClick,
    };
    
  • Question 111

    Can I dispatch an action in reducer?

    Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

  • Question 112

    How to access Redux store outside a component?

    You just need to export the store from the module where it created with createStore(). Also, it shouldn't pollute the global window object.

    store = createStore(myReducer);
    
    export default store;
    
  • Question 113

    What are the drawbacks of MVW pattern?

    1. DOM manipulation is very expensive which causes applications to behave slow and inefficient.
    2. Due to circular dependencies, a complicated model was created around models and views.
    3. Lot of data changes happens for collaborative applications(like Google Docs).
    4. No way to do undo (travel back in time) easily without adding so much extra code.
  • Question 114

    Are there any similarities between Redux and RxJS?

    These libraries are very different for very different purposes, but there are some vague similarities.

    Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular. RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises. Redux uses the Reactive paradigm because the Store is reactive. The Store observes actions from a distance, and changes itself. RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this pattern.

  • Question 115

    How to reset state in Redux?

    You need to write a root reducer in your application which delegate handling the action to the reducer generated by combineReducers().

    For example, let us take rootReducer() to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action.

    const appReducer = combineReducers({
    /* your app's top-level reducers */
    });
    
    const rootReducer = (state, action) => {
    if (action.type === "USER_LOGOUT") {
    state = undefined;
    }
    
    return appReducer(state, action);
    };
    

    In case of using redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.

    const appReducer = combineReducers({
    /* your app's top-level reducers */
    });
    
    const rootReducer = (state, action) => {
    if (action.type === "USER_LOGOUT") {
    Object.keys(state).forEach((key) => {
    storage.removeItem(`persist:${key}`);
    });
    
    state = undefined;
    }
    
    return appReducer(state, action);
    };
    
  • Question 116

    What is the difference between React context and React Redux?

    You can use Context in your application directly and is going to be great for passing down data to deeply nested components which what it was designed for.

    Whereas Redux is much more powerful and provides a large number of features that the Context API doesn't provide. Also, React Redux uses context internally but it doesn't expose this fact in the public API.

  • Question 117

    Why are Redux state functions called reducers?

    Reducers always return the accumulation of the state (based on all previous and current actions). Therefore, they act as a reducer of state. Each time a Redux reducer is called, the state and action are passed as parameters. This state is then reduced (or accumulated) based on the action, and then the next state is returned. You could reduce a collection of actions and an initial state (of the store) on which to perform these actions to get the resulting final state.

  • Question 118

    How to make AJAX request in Redux?

    You can use redux-thunk middleware which allows you to define async actions.

    Let's take an example of fetching specific account as an AJAX call using fetch API:

    export function fetchAccount(id) {
    return (dispatch) => {
    dispatch(setLoadingAccountState()); // Show a loading spinner
    fetch(`/account/${id}`, (response) => {
    dispatch(doneFetchingAccount()); // Hide loading spinner
    if (response.status === 200) {
    dispatch(setAccount(response.json)); // Use a normal function to set the received state
    } else {
    dispatch(someError);
    }
    });
    };
    }
    
    function setAccount(data) {
    return { type: "SET_Account", data: data };
    }
    
  • Question 120

    What is the proper way to access Redux store?

    The best way to access your store in a component is to use the connect() function, that creates a new component that wraps around your existing one. This pattern is called Higher-Order Components, and is generally the preferred way of extending a component's functionality in React. This allows you to map state and action creators to your component, and have them passed in automatically as your store updates.

    Let's take an example of <FilterLink> component using connect:

    import { connect } from "react-redux";
    import { setVisibilityFilter } from "../actions";
    import Link from "../components/Link";
    
    const mapStateToProps = (state, ownProps) => ({
    active: ownProps.filter === state.visibilityFilter,
    });
    
    const mapDispatchToProps = (dispatch, ownProps) => ({
    onClick: () => dispatch(setVisibilityFilter(ownProps.filter)),
    });
    
    const FilterLink = connect(mapStateToProps, mapDispatchToProps)(Link);
    
    export default FilterLink;
    

    Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux developers almost always recommend using connect() over accessing the store directly (using context API).

    function MyComponent {
    someMethod() {
    doSomethingWith(this.context.store);
    }
    }
    
Get LinkedIn Premium at Rs 399