Top React Redux and Redux Thunk Interview Questions 2022

Top React Redux and Redux Thunk Interview Questions 2022

I compiled a list of react js, redux, and redux-thunk interview questions, a few of which I encountered during my journey and a few of which I found on Google and prepared to answer.

Some of the Important Questions need to Prepare for the ReactJS Interview

  1. What are the states of Promise? Explain?
  2. What is SSR (Server Side Rendering) in React?
  3. What is the use of it?
  4. Suppose you want to stop re-rendering of the child component? How will you do it? Explain in terms of both - class components and functional components.
  5. What is the Pure component?
  6. How to pass data from child component to parent component?
  7. Could you explain one practical example where you have created HOC(Higher Order Components)?
  8. What is the difference between Virtual DOM and Real DOM?
  9. Explain the Working of React? How the React Works and What will be the process to render the element to the browser? How have you handled the State management in your project? Could you explain the structure you have followed?
  10. Redux: Why is it important to use? What does it solve?
  11. How have you handled API calls in your application?
  12. Have you used Redux saga or thunk? -> If yes then explain why you need thunk or saga? What does it solve? Explain the difference between Saga and thunk.
  13. Have you used Context API? Could you explain the difference between Context API and Redux?
  14. What are the new Lifecycle Methods introduced in React? Can you explain them in detail? And also there are some Lifecycle methods deprecated Could you explain which are they and Why they have been deprecated?
  15. Can you explain let and var with respect to hoisting? How will they differ?
  16. Explain the difference between functional and class components.
  17. Explain the difference between props and states.
  18. Explain the difference between Stateless and stateful components.
  19. Explain the difference between controlled and uncontrolled components.
  20. Explain About React. lazy and also explain the what is the use ofSuspense in the react lazyloading

Some Important Questions And Answer of React, Redux Interview Question

1. What will be the output of the below code and why explain it.

var a = 1+ '2' + 5 + 7

console.log(a);

1257

2. What will be the output of the below code and explain.

for(let i= 0; i<5;i++) {} console.log(i); i is not defined because i is block-level

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. It can be said that a variable declared with var is defined throughout the program as compared to let.

3. What are the Updates in ES6 React?

  • Classes.
  • Arrow Functions.
  • Variables (let, const, var)
  • Array Methods like. map()
  • Destructuring.
  • Modules.
  • Ternary Operator.
  • Spread Operator.

4. What is the difference between Arrow function and Normal functions in Reactjs?

  • 1. Syntax

var add = function(x,y) { return x + y; }; // ES6 let add = (x, y) => { return x + y };

  • 2. Arguments binding

Arrow functions do not have an arguments binding. However, they have access to the arguments object of the closest non-arrow parent function. Named and rest parameters are heavily relied upon to capture the arguments passed to arrow functions.

In case of a regular function: let myFunc = { showArgs(){ console.log(arguments); } }; myFunc.showArgs(1, 2, 3, 4); In case of an arrow function: let myFunc = { showArgs : () => { console.log(...arguments); } }; myFunc.showArgs(1, 2, 3, 4);

  • 3. Use of this keyword

Unlike regular functions, arrow functions do not have their own. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

Arrow Functions

let me = { name: "Ashutosh Verma", thisInArrow:() => { console.log("My name is " + this.name); // no 'this' binding here },

Regular Function

thisInRegular(){ console.log("My name is " + this.name); // 'this' binding works here } }; me.thisInArrow(); me.thisInRegular();

  • 4. Using new keyword

Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword.

However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.

  • 5. No duplicate named parameters

Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.

5. What are the states of Promise? Explain?

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code.

Multiple callback functions would create callback hell that leads to unmanageable code. Also, it is not easy for any user to handle multiple callbacks at the same time.

Events were not good at handling asynchronous operations.

Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.

Benefits of Promises

1. Improves Code Readability

2. Better handling of asynchronous operations

3. Better flow of control definition in asynchronous logic

4. Better Error Handling

A Promise has four states:

  • fulfilled: Action related to the promise succeeded
  • rejected: Action related to the promise failed
  • pending: Promise is still pending i.e. not fulfilled or rejected yet
  • settled: Promise has fulfilled or rejected

var promise = new Promise(function(resolve, reject) {} then(function() { console.log('Success, You are a GEEK'); }).catch(function() { console.log('Some error has occurred'); });

function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); }

async function f1() { var x = await resolveAfter2Seconds(10); console.log(x); // 10 }

f1();

If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

6. What is SSR (Server Side Rendering) in React? What is the use of it?

  • In Client-side rendering, your browser downloads a minimal HTML page. It renders the JavaScript and fills the content into it.
  • Server-side rendering, on the other hand, renders the React components on the server. The output is HTML content.

Cons of Rendering React on the Server

SSR can improve performance if your application is small. But it can also degrade performance if it is heavy.

  • It increases response time (and it can be worse if the server is busy).
  • It increases response size, which means the page takes longer to load.
  • It increases the complexity of the application.

When should you use Server Side Rendering?

1. SEO 2. Improve performance

How does it Work? — (4 Simple Steps)

  • Create a fresh Redux Store on every request.
  • Optionally dispatch some actions.
  • Get the state out of the Store and perform SSR.
  • Send the state obtained in the previous step along with the response.

7. Suppose you want to stop re-rendering of the child component? How will you do it? Explain in terms of both - class components and functional components?

A component can re-render even if its props don’t change. More often than not this is due to a parent component re-rendering causing the child to re-render.

To avoid this, we can wrap the child component in React.memo() to ensure it only re-renders if props have changed:

When does React decide to re-render a component?

  • The first render gets triggered after the componentWillMount lifecycle.
  • It then gets triggered after the React componentWillUpdate lifecycle.

Stop Rendering in Functional Component

function SubComponent({ text }) { return ( SubComponent: { text } ); } const MemoizedSubComponent = React.memo(SubComponent);

The memoized version of the component above will now compare props and only re-render if they have changed.

For such a small component this may not make a huge difference, but if such a component were rendered thousands of times the performance benefits would quickly start to compound.

Stop Rendering inClass Component

To avoid re-rendering per component you will use the shouldComponentUpdate() lifecycle

When to use React shouldComponentUpdate?

React shouldComponentUpdate is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed.

Only use this method if a component will stay static or pure.

The React shouldComponentUpdate method requires you to return a boolean value.

8. When to use the Class Component and the Functional Component in ReactJS?

In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props.

Whenever we have the use case with the State of the component and rendering the UI based on the Component State, use the Class Components

Class Components should be preferred whenever we have the requirement with the state of the component.

In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props.

Whenever we have the use case with the State of the component and rendering the UI based on the Component State, use the Class Components Class Components should be preferred whenever we have the requirement with the state of the component.

functional components are faster than class components,

if you need lifecycle hooks you should probably use a class component.

Functional Component Class Component
A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element. A class component requires you to extend from React. Component and create a render function that returns a React element.
There is no render method used in functional components. It must have the render() method returning HTML
Also known as Stateless components as they simply accept data and display them in some form, and they are mainly responsible for rendering UI. Also known as Stateful components because they implement logic and state.
React lifecycle methods (for example, componentDidMount) cannot be used in functional components React lifecycle methods can be used inside class components (for example, componentDidMount).
Hooks can be easily used in functional components. It requires different syntax inside a class component to implement hooks.
example: const [name,SetName]= React.useState(‘ ‘) example: constructor(props) { super(props); this.state = {name: ‘ ‘} }
Constructors are not used. Constructor is used as it needs to store state
functional components are faster than class components, Class Component is low compared to function
Functional components render the UI based on the props. Class components render the State UI based on the state in class.

What Are Class Components?

Class components are sometimes categorized as smart or stateful components because they implement logic and state. They’re ES6 classes and contain the Component class in React. Lifecycle methods can be used inside these components ( componentDidUpdate, componentDidMount, etc.).

Class components are a bit more complex because you have to keep track of not only lifecycle methods but also their side effects such as re-rendering, and data flow management.

Functional Components

Functional components are JavaScript (or ES6) functions that return React elements. They’re a bit easier to understand because there isn’t as much going on as there would be in a class component. They can also be written as simple JS functions or as an arrow function using ES6 syntax, and their props are passed in as arguments (if any).

Pros of Functional Component

Easier to test: You don’t have to worry about hidden state and there aren’t as many side effects when it comes to functional components, so for every input, the functions will have exactly one output.

Easier to read/write: The syntax is less complex than that of class components, and it’s easier to read due to knowing how much you can’t do with functional components already. The use of prop destructuring makes it really beneficial to see what’s going on and what’s coming out of the component.

Easier to debug: Again, functional components depend on the props they are given and don’t rely on the state. There isn’t a reason to console.log() your state to constantly understand the changes that are going on.

Cons of Functional Component

Relearning new syntax: The syntax could be unusual at first glance and difficult to pick up because of how long class components have been around. In classes, you declare a render function. With functions, you don’t.

For passing around props in classes, you could either send them as class properties to the component or declare default props below the component. In contrast, functional components send props as arguments. Differences like these can be challenging for other devs to understand if they’re not used to writing their apps this way.

Performance optimization: There isn’t really a difference in terms of which components benefit you more performance-wise; however, since functional components don’t have access to methods like shouldComponentUpdate and PureComponent, it could be a bit of an inconvenience to optimize them for performance.

Reasons as follows to use:

Functional components is much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks

You end up with less code

It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component

The React team mentioned that there may be a performance boost for functional components in future React versions

There is one difference in the syntax. A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element. A class component requires you to extend from React.Component and create a render function that returns a React element. This requires more code but will also give some benefits

There are pros and cons in both styles but I would like to conclude that functional components are taking over modern React in the foreseeable future.

As we noticed in the examples, a functional component is written shorter and simpler, which makes it easier to develop, understand, and test. Class components can also be confusing with so many uses of this. Using functional components can easily avoid this kind of a mess and keep everything clean.

It should also be noted that the React team is supporting more React hooks for functional components that replace or even improve upon class components. To follow up, the React team mentioned in earlier days that they will make performance optimizations in functional components by avoiding unnecessary checks and memory allocations. And as promising as it sounds, new hooks are recently introduced for functional components such as useState or useEffect while also promising that they are not going to obsolete class components.

The team is seeking to gradually adopt functional components with hooks in newer cases, which means that there is no need to switch over the existing projects that utilize class components to the entire rewrite with functional components so that they can remain consistent.

Again, there are a lot of valid coding styles in React. Yet I prefer using functional components over class components for those reasons listed above.

To sum up everything above:

Сlass components were the only option to add states to components and manipulate lifecycle. However, it has changed since the introduction of Hooks, which gave the same opportunities to functional components as classes had.

The major difference is the syntax. It relates to the way we declare components, pass props, handle states, manage the lifecycle.

Function components capture the props and state by default. It is not a bug, but a feature of functional components.

Functional components require less code to write an equal component. However, that doesn’t mean that functional components are more readable and convenient to use. If a developer is used to working with object-oriented programming, he finds using class components much more comfortable.

Those who are used to functional programming like functional components more than class components.

There are two most popular tools to test functional and class components: Enzyme and Jest. They work great for both types of components.

There is no big difference in render time between class and functional components.

9.How to pass data from child component to parent component?

Following are the steps to pass data from child component to parent component:

  1. In the parent component, create a callback function. This callback function will retrieve the data from the child component.
  2. Pass the callback function to the child as a props from the parent component.
  1. The child component calls the parent callback function using props and passes the data to the parent component.

Parent Component

import React from 'react'; import Child from './Child' class App extends React.Component{ state = { name: "", } handleCallback = (childData) =>{ this.setState({name: childData}) } render(){ const {name} = this.state; return( <div> <Child parentCallback = {this.handleCallback}/> {name} </div> ) } } export default App

Child Component

import React from 'react' class Child extends React.Component{ onTrigger = (event) => { this.props.parentCallback(event.target.myname.value); event.preventDefault(); } render(){ return( <div> <form onSubmit = {this.onTrigger}> <input type = "text" name = "myname" placeholder = "Enter Name"/> <br></br><br></br> <input type = "submit" value = "Submit"/> <br></br><br></br> </form> </div> ) } } export default Child

10. What are the differences between controlled and uncontrolled components?

Controlled component:

In a controlled component, the value of the input element is controlled by React. We store the state of the input element inside the code, and by using event-based callbacks, any changes made to the input element will be reflected in the code as well.

When a user enters data inside the input element of a controlled component, the onChange function gets triggered and inside the code, we check whether the value entered is valid or invalid. If the value is valid, we change the state and re-render the input element with the new value.

function FormValidation(props) {

let [inputValue, setInputValue] = useState("");

let updateInput = e => {

setInputValue(e.target.value);

};

return (

<div>

<form>

<input type="text" value={inputValue} onChange={updateInput} />

</form>

</div>

);

}

Uncontrolled component:

In an uncontrolled component, the value of the input element is handled by the DOM itself. Input elements inside uncontrolled components work just like normal HTML input form elements.

The state of the input element is handled by the DOM. Whenever the value of the input element is changed, event-based callbacks are not called. Basically, react does not perform any action when there are changes made to the input element.

function FormValidation(props) {

let inputValue = React.createRef();

let handleSubmit = e => {

alert(`Input value: ${inputValue.current.value}`);

e.preventDefault();

};

return (

<div>

<form onSubmit={handleSubmit}>

<input type="text" ref={inputValue} />

<button type="submit">Submit</button>

</form>

</div>

);

}

11. Explain About Store in reactjs and the Method used in Redux Store?

A store is an immutable object tree in Redux. A store is a state container that holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer.

Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below −

import { createStore } from 'redux';

import reducer from './reducers/reducer'

const store = createStore(reducer);

A createStore function can have three arguments. The following is the syntax −

createStore(reducer, [preloadedState], [enhancer])

A reducer is a function that returns the next state of an app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance the store with third-party capabilities.

A store has three important methods as given below −

getState

It helps you retrieve the current state of your Redux store.

The syntax for getState is as follows −

store.getState()

dispatch

It allows you to dispatch an action to change a state in your application.

The syntax for dispatch is as follows −

store.dispatch({type:'ITEMS_REQUEST'})

subscribe

It helps you register a callback that Redux stores will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically.

The syntax for dispatch is as follows −

store.subscribe(()=>{ console.log(store.getState());})

Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code −

const unsubscribe = store.subscribe(()=>{console.log(store.getState());});

unsubscribe();

Redux Fundamentals, Part 1: Redux Overview | Redux

12. Can we use store outside React components? Explain

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.

MyStore.js

const store = createStore(myReducer);

export store;

or

const store = createStore(myReducer);

export default store;

MyClient.js

import {store} from './MyStore'

store.dispatch(...)

or if you used the default

import store from './MyStore'

store.dispatch(...)

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId)

{ // check if user store exists and return or create it. }

export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

13.Explain Context API with the practical example.

React Context is a way to manage a state globally.

It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone

According to the React docs, Context provides a way to pass data through the component tree from parent to child components, without having to pass props down manually at each level.

The Problem without Context API

The state should be held by the highest parent component in the stack that requires access to the state.

To illustrate, we have many nested components. The components at the top and bottom of the stack need access to the state.

To do this without Context, we will need to pass the state as "props" through each nested component. This is called "prop drilling".

Passing "props" through nested components:

import { useState } from "react";

import ReactDOM from "react-dom";

function Component1() {

const [user, setUser] = useState("Jesse Hall");

return (

<>

<h1>{`Hello ${user}!`}</h1>

<Component2 user={user} />

</>

);

}

function Component2({ user }) {

return (

<>

<h1>Component 2</h1>

<Component3 user={user} />

</>

);

}

function Component3({ user }) {

return (

<>

<h1>Component 3</h1>

<Component4 user={user} />

</>

);

}

function Component4({ user }) {

return (

<>

<h1>Component 4</h1>

<Component5 user={user} />

</>

);

}

function Component5({ user }) {

return (

<>

<h1>Component 5</h1>

<h2>{`Hello ${user} again!`}</h2>

</>

);

}

ReactDOM.render(<Component1 />, document.getElementById("root"));

The Solution

The solution is to create context.

Create Context

To create context, you must Import createContext and initialize it:

import { useState, createContext } from "react";

import ReactDOM from "react-dom";

const UserContext = createContext()

Next, we'll use the Context Provider to wrap the tree of components that need the state Context.

Context Provider

Wrap child components in the Context Provider and supply the state value.

function Component1() {

const [user, setUser] = useState("Jesse Hall");

return (

<UserContext.Provider value={user}>

<h1>{`Hello ${user}!`}</h1>

<Component2 user={user} />

</UserContext.Provider>

);

}

Now, all components in this tree will have access to the user Context.

Use the useContext Hook

In order to use the Context in a child component, we need to access it using the useContext Hook.

First, include the useContext in the import statement:

import { useState, createContext, useContext } from "react";

Then you can access the user Context in all components:

function Component5() {

const user = useContext(UserContext);

return (

<>

<h1>Component 5</h1>

<h2>{`Hello ${user} again!`}</h2>

</>

);

}

Example Code for Context API

import { useState, createContext, useContext } from "react";

import ReactDOM from "react-dom";

const UserContext = createContext();

function Component1() {

const [user, setUser] = useState("Jesse Hall");

return (

<UserContext.Provider value={user}>

<h1>{`Hello ${user}!`}</h1>

<Component2 user={user} />

</UserContext.Provider>

);

}

function Component2() {

return (

<>

<h1>Component 2</h1>

<Component3 />

</>

);

}

function Component3() {

return (

<>

<h1>Component 3</h1>

<Component4 />

</>

);

}

function Component4() {

return (

<>

<h1>Component 4</h1>

<Component5 />

</>

);

}

function Component5() {

const user = useContext(UserContext);

return (

<>

<h1>Component 5</h1>

<h2>{`Hello ${user} again!`}</h2>

</>

);

}

ReactDOM.render(<Component1 />, document.getElementById("root"));

13. What are Fragments in React and use of Fragments - React. Fragments?

React.Fragments A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

14. Explain React Router? Can you explain the 3 React Router primary categories in detail Explained

We wrap our content first with <BrowserRouter>.

Then we define our <Routes>. An application can have multiple <Routes>. Our basic example only uses one.

<Route>s can be nested. The first <Route> has a path of / and renders the Layout component.

The nested <Route>s inherit and add to the parent route. So the blogs path is combined with the parent and becomes /blogs.

The Home component route does not have a path but has an index attribute. That specifies this route as the default route for the parent route, which is /.

Setting the path to * will act as a catch-all for any undefined URLs. This is great for a 404 error page.

import ReactDOM from "react-dom";

import { BrowserRouter, Routes, Route } from "react-router-dom";

import Layout from "./pages/Layout";

import Home from "./pages/Home";

import Blogs from "./pages/Blogs";

import Contact from "./pages/Contact";

import NoPage from "./pages/NoPage";

export default function App() {

return (

<BrowserRouter>

<Routes>

<Route path="/" element={<Layout />}>

<Route index element={<Home />} />

<Route path="blogs" element={<Blogs />} />

<Route path="contact" element={<Contact />} />

<Route path="*" element={<NoPage />} />

</Route>

</Routes>

</BrowserRouter>

);

}

ReactDOM.render(<App />, document.getElementById("root"));

Routing is a process in which a user is directed to different pages based on their action or request.

React Router(SPA) is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

Let us create a simple application to React to understand how the React Router works. The application will contain three components: home component, about a component, and contact component. We will use React Router to navigate between these components.

npm install – -save react-router-dom

After installing react-router-dom, add its components to your React application.

Adding React Router Components: The Main Components of React Router are:

  • BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState, and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.
  • Routes: It’s a new component introduced in the v6 and an upgrade of the component. The main advantages of Routes over Switch are:
    • Relative s and s
    • Routes are chosen based on the best match instead of being traversed in order.
  • Route: Route is the conditionally show component that renders some UI when its path matches the current URL.
  • Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML

import React, { Component } from 'react';

import { BrowserRouter as Router,Routes, Route, Link } from 'react-router-dom';

import Home from './component/home';

import About from './component/about';

import Contact from './component/contact';

import './App.css';

class App extends Component {

render() {

return (

<Router>

<div className="App">

<ul className="App-header">

<li>

<Link to="/">Home</Link>

</li>

<li>

<Link to="/about">About Us</Link>

</li>

<li>

<Link to="/contact">Contact Us</Link>

</li>

</ul>

<Routes>

<Route exact path='/' element={< Home />}></Route>

<Route exact path='/about' element={< About />}></Route>

<Route exact path='/contact' element={< Contact />}></Route>

</Routes>

</div>

</Router>

);

}

}

export default App;

Now, we you can click on the links and navigate to different components. React Router keeps your application UI in sync with the URL.

15. What is Reduxthunk? Why do you need to use Redux Thunk?

What is a "thunk"?

The word "thunk" is a programming term that means "a piece of code that does some delayed work". Rather than execute some logic now, we can write a function body or code that can be used to perform the work later.

For Redux specifically, "thunks" are a pattern of writing functions with logic inside that can interact with a Redux store's dispatch and getState methods.

Using thunks requires the redux-thunk middleware to be added to the Redux store as part of its configuration.

Thunks are the standard approach for writing async logic in Redux appsand are commonly used for data fetching. However, they can be used for a variety of tasks and can contain both synchronous and asynchronous logic.

A thunk function is a function that accepts two arguments: the Redux store dispatch method, and the Redux store getState method. Thunk functions are not directly called by application code. Instead, they are passed to store.dispatch():

const thunkFunction = (dispatch, getState) => { // logic here that can dispatch actions or read state } store.dispatch(thunkFunction)

Why Use Thunks?

Thunks allow us to write additional Redux-related logic separate from a UI layer. This logic can include side effects, such as async requests or generating random values, as well as logic that requires dispatching multiple actions or access to the Redux store state.

It's common to have logic directly in components, such as making an async request in a click handler or a useEffect hook and then processing the results. However, it's often necessary to move as much of that logic as possible outside the UI layer. This may be done to improve testability of the logic, to keep the UI layer as thin and "presentational" as possible, or to improve code reuse and sharing.

Thunk Use Cases

Because thunks are a general-purpose tool that can contain arbitrary logic, they can be used for a wide variety of purposes. The most common use cases are:

  • Moving complex logic out of components

  • Making async requests or other async logic

  • Writing logic that needs to dispatch multiple actions in a row or overtime

  • Writing logic that needs access to getState to make decisions or include other state values in an action

Thunks are "one-shot" functions, with no sense of a lifecycle. They also cannot see other dispatched actions. So, they should not generally be used for initializing persistent connections like WebSockets, and you can't use them to

Because it is a Redux tool, you will also need to have Redux set up. Once installed, it is enabled using applyMiddleware():

import { createStore, applyMiddleware } from 'redux';

import thunk from 'redux-thunk';

import rootReducer from './reducers/index';

const store = createStore(

rootReducer,

applyMiddleware(thunk)

);

How to Use Redux Thunk

Once Redux Thunk has been installed and included in your project with applyMiddleware(thunk), you can start dispatching actions asynchronously.

For example, here's a simple increment counter:

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {

return {

type: INCREMENT_COUNTER

};

}

function incrementAsync() {

return dispatch => {

setTimeout(() => {

// You can invoke sync or async actions with `dispatch`

dispatch(increment());

}, 1000);

};

}

And here's how set up success and failure actions after polling an API:

const GET_CURRENT_USER = 'GET_CURRENT_USER';

const GET_CURRENT_USER_SUCCESS = 'GET_CURRENT_USER_SUCCESS';

const GET_CURRENT_USER_FAILURE = 'GET_CURRENT_USER_FAILURE';

const getUser = () => {

return (dispatch) => { //nameless functions

// Initial action dispatched

dispatch({ type: GET_CURRENT_USER });

// Return promise with success and failure actions

return axios.get('/api/auth/user').then(

user => dispatch({ type: GET_CURRENT_USER_SUCCESS, user }),

err => dispatch({ type: GET_CURRENT_USER_FAILURE, err })

);

};

};

16.What are the differences between == and === operator?

What is == in JavaScript?

Double equals (==) is a comparison operator, which transforms the operands having the same type before comparison.

So, when you compare a string with a number, JavaScript converts any string to a number. An empty string is always converted to zero. A string with no numeric value is converted to NaN (Not a Number), which returns false.

What is === in JavaScript?

=== (Triple equals) is a strict equality comparison operator in JavaScript, which returns false for the values which are not of a similar type. This operator performs type casting for equality. If we compare 2 with “2” using ===, then it will return a false value.

17. What are the different phases of the component lifecycle?

There are four different phases in the lifecycle of React components. They are:

  • Initialization: During this phase, React components will prepare by setting up the default props and initial state for the upcoming tough journey.
  • Mounting: Mounting refers to putting the elements into the browser DOM. Since React uses VirtualDOM, the entire browser DOM which has been currently rendered would not be refreshed. This phase includes the lifecycle methods componentWillMount and componentDidMount.
  • Updating: In this phase, a component will be updated when there is a change in the state or props of a component. This phase will have lifecycle methods like componentWillUpdate, shouldComponentUpdate, render, and componentDidUpdate.
  • Unmounting: In this last phase of the component lifecycle, the component will be removed from the DOM or will be unmounted from the browser DOM. This phase will have the lifecycle method named componentWillUnmount.

18. Explain the Working of React? How the React Works and What will be the process to render the element to the browser? How have you handled the State management in your project? Could you explain the structure you have followed?

A virtual DOM is a lightweight JavaScript object which originally is just a copy of the real DOM. It is a node tree that lists the elements, their attributes, and content as Objects and their properties. React render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

  1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.Virtual DOM 1 - What Is ReactJS? - Edureka
  2. Then the difference between the previous DOM representation and the new one is calculated.

Virtual DOM 2 - React Interview Questions - Edureka

  1. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.

Virtual DOM 3 - React Interview Questions - Edureka

  • React is a front-end JavaScript library developed by Facebook in 2011.
  • It follows the component-based approach which helps in building reusable UI components.
  • It is used for developing complex and interactive web and mobile UI.
  • Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.

MODAL VIEW CONTROLLER MVC Architecture

Manage data and rules of the application

  • It uses the virtual DOM instead of the real DOM.
  • It uses server-side rendering.
  • It follows unidirectional data flow or data binding.

Differences between functional and class-Components

  • Declaration
  • Handling props
  • Handling state

Real DOM

Virtual DOM

1. It updates slowly.

1. It updates faster.

2. Can directly update HTML.

2. Can’t directly update HTML.

3. Creates a new DOM if element updates.

3. Updates the JSX if element updates.

4. DOM manipulation is very expensive.

4. DOM manipulation is very easy.

5. Too much memory wastage.

5. No memory wastage.

Explain About the Testing Tool Used In Reactjs?

Jest and Enzyme

  • Both Jest and Enzyme are specifically designed to test React applications, Jest can be used with any other Javascript app but Enzyme only works with React.
  • Jest can be used without Enzyme to render components and test with snapshots, Enzyme simply adds additional functionality.
  • Enzyme can be used without Jest, however Enzyme must be paired with another test runner if Jest is not used.

As described, we will use:

  • Jest as the test runner, assertion library, and mocking library
  • Enzyme to provide additional testing utilities to interact with elements

More Important Questions Asked In ReactJS interview Questions :

  • Does React UseStateHook update immediately?

  • What are the advantages of using React Hooks?

  • What can you tell me about JSX?

  • What is prop drilling and how can you avoid it?

  • What is StrickModein React?

  • What is the difference between ShadowDOM and VirtualDOM?

  • Why should we not update the state directly?

  • Can web browsers read JSX directly?

  • Why use React instead of other frameworks, like Angular?

  • What is the difference between the ES6 and ES5 standards?

  • What is an event in React?

  • What are synthetic events in React?

  • Why is there a need for using keys in Lists?

  • What is an arrow function and how is it used in React?

  • What are the components in React?

  • What is the use of render() in React?

  • What are the differences between state and props?

  • What are the components of Redux?

  • How is React routing different from conventional routing? Why do we need to React Router?

  • State the core principles of Redux.

  • What are the advantages of using Redux?

  • Is it true that Redux can only be used with React?

  • What do you understand about Redux Toolkit?

  • What are some of the major features of Redux DevTools?

  • Is it necessary to keep all the component states in the Redux store?

  • Highlight the key differences between mapStateToProps() and mapDispatchToProps()?

  • What do you understand by action in Redux's architecture?

  • Give an example of the usage of Actions in Redux's architecture.

  • Where can we use Redux?

  • What are constants in Redux?

  • Show using code how constants can be used in Redux.

  • What are the reducers in Redux's architecture? Show with an example how reducers are used in Redux.

  • Explain the typical data flow in an application made using React and Redux (Redux Lifecycle for an application).

  • What is the mental model of redux-saga?

  • Describe what is meant by a "store" in Redux.

  • Name all the Redux Store methods.

  • Give an example depicting the usage of a Redux store.

  • Explain with an example how to set the initial state in Redux.

  • What do you understand about Redux Thunk?

  • How can we use connect from react redux?

  • How can we structure the top-level directories in Redux?

  • How can we access a redux store outside a react component?

  • Differentiate between React Redux and React's Context API.

  • What do you understand about the Redux Saga?

  • What are the things which we should never do inside a reducer?
  • How can the addition of multiple middlewares to Redux be done?

  • The states and actions are held together in Redux using?- store

  • : Do you need to keep all component states in the Redux store?

  • How to add multiple middlewares to Redux?

  • How to set the initial state in Redux?

  • What are the core principles of Redux?

  • How to use connect from react-redux?

  • What are the downsides of Redux over Flux?

  • What is the purpose of the constants in Redux?

Post comments

Leave a comment

Your email address will not be published. Required fields are marked *

Testimonials

What Our Students Say

Testinomial of notes4free , what's the Student say about notes4free,

"Very good platforms ..expecting more BCA notes"

Prajwal Shanthiniketan degree college

"Website is well-built and it looks good. It not only provides notes but also projects, resume building, aptitude tests and many more."

Ramya rrce

"I was really in a dielama on which notes to refer especially for vtu exams..Then I got to know about this website (notes4free) the notes were very clear and easy to understand and I am hoping to score very well by referring to notes4free notes."

Ashwin krishna Rajarajeswari college of engineering

"notes4free.in website is a very unique one Which I have seen so far . This platform is like all in one . I really liked a lot because it is user friendly 😊"

Pavithra Kumar Rajarajeswari college of engineering engineering

"This platform is awesome in this gets all vtu notes, interview process resume building, all types of projects all are available in one platform it's very useful to us and good initiative .. keep going on.."

Harshitha Rrce

"A very good initiative!!please do continue the same and let this reach out to more number of students all over....??"

Bhuvana B C SABS

Notes4free Blogs

Latest News & Blog

check our latest blogs updates, projects and technical blogs and courses in notes4free.

6 Best Car Insurance For College Students 2022

6 Best Car Insurance For College Students 2022

Best Car Insurance For College Students in 2022 Car Insurance For College Students 2022, students offer&nbsp;complete coverage and benefits, as well

How to earn a money from online digital marketing

How to earn a money from online digital marketing

How to Benefit from Your Digital Marketing Blog. &nbsp;

#

php projects on Online voting system using PHP and MySQL

In &quot;ONLINE VOTING SYSTEM&quot; a voter can use his/her voting right online without any difficulty. He/She has to be registered first for him/her to vote. R

Aptitude questions and answers on Permutations

Aptitude questions and answers on Permutations

Aptitude questions and answer from permutations&nbsp; 1.&nbsp;A college has 10 basketball players. A 5-member team and a cap

H.C.F and L.C.M Aptitude questions and answers

H.C.F and L.C.M Aptitude questions and answers

Aptitude questions and answers on H.C.F and L.C.M concepts&nbsp; 1) What is the HCF of 1095 and 1168? 37