DEV Community

Cover image for React/Redux Interview Questions with answers šŸš€
Suprabha
Suprabha

Posted on

React/Redux Interview Questions with answers šŸš€

I prepared list of react and redux interview question, Few question I faced in my journey and few of the question I have referred from Google itself šŸ˜‚

React Interview Questions šŸš€

Q.1. How to create components in React?
Q.2. What are the difference between a class component and functional component?
Q.3. What is difference between controlled vs uncontrolled component?
Q.4. What is children?
Q.5. What is prop drilling and how can you avoid it?
Q.6. What is Pure Component?
Q.7. Why should we not update the state directly?
Q.8. What is the purpose of callback function as an argument of setState()?
Q.9. What are synthetic events in React?
Q.10. What is "key" prop and what is the benefit of using it in arrays elements?
Q.11. Why are String Refs legacy?
Q.12. What is the difference between createElement and cloneElement?
Q.13. What is reconciliation?
Q.14. Is lazy function supports named exports?
Q.15. What are portals in React?
Q.16. What are stateless components?
Q.17. What are stateful components?
Q.18. What is the impact of indexes as keys?
Q.19. How do you memoize a component?
Q.20. Why we need to pass a function to setState()?
Q.21. Why should component names start with capital letter?
Q.22. Can you force a component to re-render without calling setState?
Q.23. What is the difference between super() and super(props) in React usin ES6 classes?
Q.24. Is it mandatory to define constructor for React component?
Q.25. What are default props?
Q.26. How to apply validation on props in React?
Q.27. Why you can't update props in React?
Q.28. What are render props?
Q.29. What is Suspense component?
Q.30. What is diffing algorithm?
Q.31. How to re-render the view when the browser is resized?
Q.32. What is React memo function?
Q.33. What is the methods order when component re-rendered?
Q.34. What are loadable components?
Q.35. How to pretty print JSON with React?
Q.36. What is render hijacking in react?
Q.37. How to use https instead of http in create-react-app?
Q.38. How can we convert functional component to pure component?


Q.1. How to create components in React?

Ans. There are two possible ways to create a component.

āœ…Functional Components:Ā This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as first parameter and return React elements:

function Greeting({ message }) {
  return <h1>{`Hello, ${message}`}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

āœ…Class Components:Ā You can also use ES6 class to define a component. The above function component can be written as:

class Greeting extends React.Component {
  render() {
    return <h1>{`Hello, ${this.props.message}`}</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Q.2. What are the difference between a class component and functional component?

Ans.

āœ…Class Components

  • Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.
  • Class components extend from React.Component.
  • In here you have to use this keyword to access the props and functions that you declare inside the class components.

āœ…Functional Components

  • Functional Components are simpler comparing to class-based functions.
  • Functional Components mainly focuses on the UI of the application, not on the behavior.
  • To be more precise these are basically render function in the class component.
  • Functional Components can have state and mimic lifecycle events using Reach Hooks

Q.3. What is difference between controlled vs uncontrolled component?


Ans.

āœ…Controlled Components
In HTML, form elements such as <input />, <textarea />, and <select /> typically maintain their own state and update it based on user input. When a user submits a form, the values from the elements mentioned above are sent with the form. With React it works differently. The component containing the form will keep track of the value of the input in its state and will re-render the component each time the callback function, e.g., onChange is fired as the state will be updated. An input form element whose value is controlled by React in this way is called a "controlled component". You could also call this a "dumb component".

āœ…Uncontrolled Components
AĀ Uncontrolled ComponentĀ is one that stores its own state internally, and you query the DOM using aĀ refĀ to find its current value when you need it. This is a bit more like traditional HTML.

Example

// Controlled:
<input type="text" value={value} onChange={handleChange} />

// Uncontrolled:
<input type="text" defaultValue="foo" ref={inputRef} />
// Use `inputRef.current.value` to read the current value of <input>
Enter fullscreen mode Exit fullscreen mode

Q.4. What is children?

Ans. In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed to components automatically as a special prop:

props.children
Enter fullscreen mode Exit fullscreen mode

There are some methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray šŸ‘¶

const MainContainer = React.createClass({
  render: function () {
    return <div>{this.props.children}</div>;
  },
});

ReactDOM.render(
  <MainContainer>
    <span>{'Hello'}</span>
    <span>{'World'}</span>
  </MainContainer>,
  node,
);
Enter fullscreen mode Exit fullscreen mode

Q.5. What is prop drilling and how can you avoid it?

Ans. While passing a prop from each component to the next in the hierarchy from the source component to the deeply nested component. This is calledĀ prop drilling.

To avoid prop drilling, a common approach is to use React context. This allows aĀ ProviderĀ component that supplies data to be defined, and allows nested components to consume context data via either aĀ ConsumerĀ component or aĀ useContextĀ hook.

Q.6. What is Pure Component?

Ans. React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

Q.7. Why should we not update the state directly?


Ans. If you try to update state directly then it won't re-render the component.

//Wrong āŒ
this.state.message = 'Not Updated';
Enter fullscreen mode Exit fullscreen mode

Instead useĀ setState()Ā method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.

//Correct āœ…
this.setState({ message: 'Updated' });
Enter fullscreen mode Exit fullscreen mode

šŸ“ Note:Ā You can directly assign to the state object either inĀ constructorĀ or using latest javascript's class field declaration syntax.

Q.8. What is the purpose of callback function as an argument of setState()

Ans. The callback function is invoked when setState finished and the component gets rendered. SinceĀ setState()Ā isĀ asynchronousĀ the callback function is used for any post action.

šŸ“ Note:Ā It is recommended to use lifecycle method rather than this callback function.

setState({ name: 'Supi' }, () => console.log('The name has updated and component re-rendered'));
Enter fullscreen mode Exit fullscreen mode

Q.9. What are synthetic events in React?

Ans. Synthetic Event is a cross-browser wrapper around the browser's native event. It's API is same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

Q.10. What is "key" prop and what is the benefit of using it in arrays of elements šŸ—?

Ans. AĀ keyĀ is a special string attribute youĀ shouldĀ include when creating arrays of elements.KeyĀ prop helps React identify which items have changed, are added, or are removed.

Most often we use ID from our data asĀ key:

const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
Enter fullscreen mode Exit fullscreen mode

When you don't have stable IDs for rendered items, you may use the itemĀ indexĀ as aĀ keyĀ as a last resort:

const todoItems = todos.map((todo, index) => <li key={index}>{todo.text}</li>);
Enter fullscreen mode Exit fullscreen mode

šŸ“ Note:

  1. UsingĀ indexesĀ forĀ keysĀ isĀ not recommendedĀ if the order of items may change. This can negatively impact performance and may cause issues with component state.
  2. If you extract list item as separate component then applyĀ keysĀ on list component instead ofĀ liĀ tag.
  3. There will be a warning message in the console if theĀ keyĀ prop is not present on list items.

Q.11. Why are String Refs legacy?

Ans. If you worked with React before, you might be familiar with an older API where theĀ refĀ attribute is a string, likeĀ ref={'textInput'}, and the DOM node is accessed asĀ this.refs.textInput. We advise against it becauseĀ string refs have below issues, and are considered legacy. String refs wereĀ removed in React v16.

  1. TheyĀ force React to keep track of currently executing component. This is problematic because it makes react module stateful, and thus causes weird errors when react module is duplicated in the bundle.
  2. They areĀ not composableĀ ā€” if a library puts a ref on the passed child, the user can't put another ref on it. Callback refs are perfectly composable.
  3. TheyĀ don't work with static analysisĀ like Flow. Flow can't guess the magic that framework does to make the string ref appear onĀ this.refs, as well as its type (which could be different). Callback refs are friendlier to static analysis.
  4. It doesn't work as most people would expect with the "render callback" pattern (e.g. )
class MyComponent extends Component {
    renderRow = (index) => {
        // This won't work. Ref will get attached to DataTable rather than MyComponent:
        return <input ref={'input-' + index} />;

        // This would work though! Callback refs are awesome.
        return <input ref={(input) => (this['input-' + index] = input)} />;
    };

   render() {
        return <DataTable data={this.props.data} renderRow={this.renderRow} />;
   }
}
Enter fullscreen mode Exit fullscreen mode

Q.12. What is the difference between createElement and cloneElement?

Ans. JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.

Q.13. What is reconciliation?

Ans. When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

Q.14. Is lazy function supports named exports?

Ans. No, currentlyĀ React.lazyĀ function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and donā€™t pull unused components. Let's take a component file which exports multiple named components,

Example:

// FewComponents.js
export const SomeComponent = /* ... */;
export const UnusedComponent = /* ... */;
Enter fullscreen mode Exit fullscreen mode

and reexportĀ FewComponents.jsĀ components in an intermediate fileĀ IntermediateComponent.js

// IntermediateComponent.js
export { SomeComponent as default } from './FewComponents.js';
Enter fullscreen mode Exit fullscreen mode

Now you can import the module using lazy function as below,

import React, { lazy } from 'react';
const SomeComponent = lazy(() => import('./IntermediateComponent.js'));
Enter fullscreen mode Exit fullscreen mode

Q.15. What are portals in React?

Ans. PortalĀ is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container);
Enter fullscreen mode Exit fullscreen mode

The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM element.

Q.16. What are stateless components?

Ans. If the behaviour is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components.

Q.17. What are stateful components?

Ans. If the behaviour of a component is dependent on theĀ stateĀ of the component then it can be termed as stateful component. TheseĀ stateful componentsĀ are alwaysĀ class componentsĀ and have a state that gets initialized in theĀ constructor.

class App extends Component {
   constructor(props) {
     super(props);
     this.state = { count: 0 };
   }

   render() {
     // ...
   }
}
Enter fullscreen mode Exit fullscreen mode

React 16.8 Update:

Hooks let you use state and other React features without writing classes.

The Equivalent Functional Component

import React, {useState} from 'react';

const App = (props) => {
   const [count, setCount] = useState(0);

   return (
     // JSX
   )
}
Enter fullscreen mode Exit fullscreen mode

Q.18. What is the impact of indexes as keys?

Ans. Keys should be stable, predictable, and unique so that React can keep track of elements.

In the below code snippet each element's key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do.

{
    todos.map((todo, index) => <Todo {...todo} key={index} />)
}

Enter fullscreen mode Exit fullscreen mode

If you use element data for unique key, assuming todo.id is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.

{
    todos.map((todo) => <Todo {...todo} key={todo.id} />)
}
Enter fullscreen mode Exit fullscreen mode

Q.19. How do you memoize a component?

Ans. Since React v16.6.0, we have aĀ React.memo. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it.

const MemoComponent = React.memo(function MemoComponent(props) {
    /* render using props */
});

// OR

export default React.memo(MyFunctionComponent);
Enter fullscreen mode Exit fullscreen mode

Q.20. Why we need to pass a function to setState()?

Ans. The reason behind for this is thatĀ setState()Ā is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately afterĀ setState()Ā is called. That means you should not rely on the current state when callingĀ setState()ā€Šsince you can't be sure what that state will be. The solution is to pass a function toĀ setState(), with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature ofĀ setState().

Let's say the initial count value is zero. After three consecutive increment operations, the value is going to be incremented only by one.

// assuming this.state.count === 0
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
// this.state.count === 1, not 3

Enter fullscreen mode Exit fullscreen mode

If we pass a function toĀ setState(), the count gets incremented correctly.

this.setState((prevState, props) => ({
count: prevState.count + props.increment,
}));
// this.state.count === 3 as expected
Enter fullscreen mode Exit fullscreen mode

Q.21. Why should component names start with capital letter?

Ans. If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.

class OneComponent extends Component {
// ...
}
Enter fullscreen mode Exit fullscreen mode

You can define component class which name starts with lowercase letter, but when it's imported it should have capital letter. Here lowercase is fine:

class myComponent extends Component {
   render() {
     return <div />;
   }
}

export default myComponent;
Enter fullscreen mode Exit fullscreen mode

While when imported in another file it should start with capital letter:

import MyComponent from './MyComponent';
Enter fullscreen mode Exit fullscreen mode

What are the exceptions on React component naming?

The component names should start with a uppercase letter but there are few exceptions on this convention. The lowercase tag names with a dot (property accessors) are still considered as valid component names.

For example the below tag can be compiled to a valid component,

render() {
    return (
        <obj.component /> // `React.createElement(obj.component)`
    )
}
Enter fullscreen mode Exit fullscreen mode

Q.22. Can you force a component to re-render without calling setState?

Ans. By default, when your component's state or props change, your component will re-render. If yourĀ render()Ā method depends on some other data, you can tell React that the component needs re-rendering by callingĀ forceUpdate().

component.forceUpdate(callback);
Enter fullscreen mode Exit fullscreen mode

It is recommended to avoid all uses ofĀ forceUpdate()Ā and only read fromĀ this.propsĀ andĀ this.stateĀ inĀ render().

Q.23. What is the difference between super() and super(props) in React usin ES6 classes?

Ans. When you want to accessĀ this.propsĀ inĀ constructor()Ā then you should pass props toĀ super()Ā method.

UsingĀ super(props):

class MyComponent extends React.Component {
   constructor(props) {
     super(props);
     console.log(this.props); // { name: 'Supi', ... }
   }
}
Enter fullscreen mode Exit fullscreen mode

UsingĀ super():

class MyComponent extends React.Component {
   constructor(props) {
     super();
     console.log(this.props); // undefined
   }
}
Enter fullscreen mode Exit fullscreen mode

OutsideĀ constructor()Ā both will display same value forĀ this.props.

Q.24. Is it mandatory to define constructor for React component?

Ans. No, it is not mandatory. i.e, If you donā€™t initialize state and you donā€™t bind methods, you donā€™t need to implement a constructor for your React component.

Q.25. What are default props?

Ans. The defaultProps are defined as a property on the component class to set the default props for the class. This is used for undefined props, but not for null props.

For example, let us create color default prop for the button component,

class MyButton extends React.Component {
  // ...
}

MyButton.defaultProps = {
  color: 'blue',
};
Enter fullscreen mode Exit fullscreen mode

If props.color is not provided then it will set the default value to 'red'. i.e, Whenever you try to access the color prop it uses default value

render() {
  return <MyButton /> ; // props.color will be set to red
}
Enter fullscreen mode Exit fullscreen mode

šŸ“ Note:Ā If you provide null value then it remains null value.

Q.26. How to apply validation on props in React?

Ans. When the application is running inĀ development mode, React will automatically check all props that we set on components to make sure they haveĀ correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled inĀ production modeĀ due to performance impact. The mandatory props are defined withĀ isRequired.

The set of predefined prop types:

  1. PropTypes.number
  2. PropTypes.string
  3. PropTypes.array
  4. PropTypes.object
  5. PropTypes.func
  6. PropTypes.node
  7. PropTypes.element
  8. PropTypes.bool
  9. PropTypes.symbol
  10. PropTypes.any

We can defineĀ propTypesĀ forĀ UserĀ component as below:

import React from 'react';
import PropTypes from 'prop-types';

class User extends React.Component {
    static propTypes = {
        name: PropTypes.string.isRequired,
        age: PropTypes.number.isRequired,
    };

    render() {
        return (
          <>
            <h1>{`Welcome, ${this.props.name}`}</h1>
            <h2>{`Age, ${this.props.age}`}</h2>
          </>
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

šŸ“ Note:Ā In React v15.5Ā PropTypesĀ were moved fromĀ React.PropTypesĀ toĀ prop-typesĀ library.

Q.27. Why you can't update props in React?

Ans. The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.

Q.28. What are render props?

Ans. Render PropsĀ is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.

<DataProvider render={(data) => <h1>{`Hello ${data.target}`}</h1>} />
Enter fullscreen mode Exit fullscreen mode

Libraries such as React Router and DownShift are using this pattern.

Q.29. What is Suspense component?

Ans. If the module containing the dynamic import is not yet loaded by the time parent component renders, you must show some fallback content while youā€™re waiting for it to load using a loading indicator. This can be done usingĀ SuspenseĀ component.

Example

const OneComponent = React.lazy(() => import('./OneComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OneComponent />
      </Suspense>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

As mentioned in the above code, Suspense is wrapped above the lazy component.

Q.30. What is diffing algorithm?

Ans. React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n3) where n is the number of elements in the tree.

In this case, for displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:

  1. Two elements of different types will produce different trees.
  2. The developer can hint at which child elements may be stable across different renders with a key prop.

Q.31. How to re-render the view when the browser is resized?

Ans. You can listen to theĀ resizeĀ event inĀ componentDidMount()Ā and then update the dimensions (widthĀ andĀ height). You should remove the listener inĀ componentWillUnmount()Ā method.

class WindowDimensions extends React.Component {
   constructor(props) {
     super(props);
     this.updateDimensions = this.updateDimensions.bind(this);
   }

   componentWillMount() {
     this.updateDimensions();
   }

   componentDidMount() {
     window.addEventListener('resize', this.updateDimensions);
   }

   componentWillUnmount() {
     window.removeEventListener('resize', this.updateDimensions);
   }

   updateDimensions() {
     this.setState({ width: window.innerWidth, height: window.innerHeight });
   }

   render() {
     return (
       <span>
         {this.state.width} x {this.state.height}
       </span>
     );
   }
}
Enter fullscreen mode Exit fullscreen mode

Q.32. What is React memo function?

Ans. Class components can be restricted from rendering when their input props are the same usingĀ PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them inĀ React.memo.

const MyComponent = React.memo(function MyComponent(props) {
  /* only rerenders if props change */
});
Enter fullscreen mode Exit fullscreen mode

Q.33. What is the methods order when component re-rendered?

Ans. An update can be caused by changes to props or state. The below methods are called in the following order when a component is being re-rendered.

  1. static getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

Q.34. What are loadable components?

Ans. If you want to do code-splitting in a server rendered app, it is recommend to use Loadable Components because React.lazy and Suspense is not yet available for server-side rendering. Loadable lets you render a dynamic import as a regular component.

Lets take an example,

import loadable from '@loadable/component';

const OtherComponent = loadable(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now OtherComponent will be loaded in a separated bundle

Q.35. How to pretty print JSON with React?

Ans. We can useĀ <pre>Ā tag so that the formatting of theĀ JSON.stringify()Ā is retained:

const data = { name: 'John', age: 42 };

class User extends React.Component {
   render() {
     return <pre>{JSON.stringify(data, null, 2)}</pre>;
   }
}

React.render(<User />, document.getElementById('container'));
Enter fullscreen mode Exit fullscreen mode

Q.36. What is render hijacking in react?

Ans. The concept of render hijacking is the ability to control what a component will output from another component. It actually means that you decorate your component by wrapping it into a Higher-Order component. By wrapping you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enables hijacking, but by using HOC you make your component behave in different way.

Q.37. How to use https instead of http in create-react-app?

Ans. You just need to useĀ HTTPS=trueĀ configuration. You can edit yourĀ package.jsonĀ scripts section:

"scripts": {
    "start": "set HTTPS=true && react-scripts start"
}
Enter fullscreen mode Exit fullscreen mode

or just runĀ set HTTPS=true && npm start

Q.38. How can we convert functional component to pure component?

Ans. We can convert functional to pure component using React.memo.

Redux Interview Questions šŸ‘©šŸ»ā€šŸ’»

Q.1. What are reducers in redux?
Q.2. How is state changed in redux?
Q.3. How Redux Form initialValues get updated from state?
Q.4. What is Redux Thunk?
Q.5. What is the difference between mapStateToProps() and mapDispatchToProps()?
Q.6. How to add multiple middlewares to Redux?
Q.7. What is React context vs React redux?
Q.8. Why React uses className over class attribute?
Q.9. What is Relay?
Q.10. How Relay is different from Redux?
Q.11. What is Combine Reducer?


Q.1. What are reducers in redux?

Ans. The reducer is a pure function that takes the previous state and an action, and returns the next state.

(previousState, action) => newState
Enter fullscreen mode Exit fullscreen mode

It's very important that the reducer staysĀ pure. Things you should never do inside a reducer:

  • Mutate its arguments;
  • Perform side effects like API calls and routing transitions;
  • Call non-pure functions, e.g. Date.now() or Math.random()

Q.2. How is state changed in redux?

Ans. 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. Instead, they express an intent to transform the state. Because all changes are centralized and happen one by one in a strict order, there are no subtle race conditions to watch out for. As actions are just plain objects, they can be logged, serialized, stored, and later replayed for debugging or testing purposes.

Q.3. How Redux Form initialValues get updated from state?

Ans. You need to addĀ enableReinitialize : trueĀ setting.

const InitializeFromStateForm = reduxForm({
  form: 'initializeFromState',
  enableReinitialize: true,
})(UserEdit);

Enter fullscreen mode Exit fullscreen mode

If yourĀ initialValuesĀ prop gets updated, your form will update too.

Q.4. What is Redux Thunk?

Ans. Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState() as parameters.

Q.5. What is the difference between mapStateToProps() and mapDispatchToProps()?

Ans.

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),
  };
};

Enter fullscreen mode Exit fullscreen mode

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));
    },
  };
};
Enter fullscreen mode Exit fullscreen mode

Recommend always using the "object shorthand" form for theĀ mapDispatchToProps

Redux wrap 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,
};
Enter fullscreen mode Exit fullscreen mode

Q.6. How to add multiple middlewares to Redux?

Ans. You can useĀ applyMiddlewareĀ where you can pass each piece of middleware as a new argument. So you just need to pass each piece of middleware you'd like. For example, you can add Redux Thunk and logger middlewares as an argument as below,

import { createStore, applyMiddleware } from 'redux'
const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore);
Enter fullscreen mode Exit fullscreen mode

Q.7. What is React context vs React redux?

Ans. 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. So you should feel much safer using Context via React Redux than directly because if it changes, the burden of updating the code will be on React Redux instead developer responsibility.

Q.8. Why React uses className over class attribute?

Ans. classĀ is a keyword in javascript and JSX is an extension of javascript. That's the principal reason why React usesĀ classNameĀ instead of class.

render() {
  return <span className="menu navigation-menu">Menu</span>
}
Enter fullscreen mode Exit fullscreen mode

Q.9. What is Relay?

Ans. Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.

Q.10. How Relay is different from Redux?

Ans. Relay is similar to Redux in that they both use a single store. The main difference is that relay only manages state originated from the server, and all access to the state is used via GraphQL queries (for reading data) and mutations (for changing data). Relay caches the data for you and optimizes data fetching for you, by fetching only changed data and nothing more.

Q.11. What is Combine Reducer?

Ans. The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore . The resulting reducer calls every child reducer, and gathers their results into a single state object.

šŸŒŸ Twitter šŸ‘©šŸ»ā€šŸ’» suprabha.me šŸŒŸ Instagram

Top comments (7)

Collapse
 
alvechy profile image
Alex Vechy • Edited

I would kindly suggest to any interviewer to ask these questions only during live coding sessions, and not just out of the blue.

Collapse
 
harisharaju1 profile image
Harish Raju

Thanks for this SuprabhašŸ˜€

Collapse
 
dev_emmy profile image
nshimiye_emmy

thanks this was helpful

Collapse
 
tomaszs2 profile image
Tom Smykowski

Great questions. I have prepared a flashcards deck to make React interview questions easier to remember:
summonthejson.com/products/summon-...

Collapse
 
atulbansal4444 profile image
Atul Bansal

Thanks a lot for this quick guide.

Collapse
 
carleytripp profile image
Carley Tripp

Thank you for putting this together!

Collapse
 
rohithbubby profile image
RohithBubby

This was really helpful :)