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
-
Pros and cons of functional and class components,
-
Redux architecture
-
How to handle Fetching data in the UseEffect hook
-
How to implement API functions using Axios and setting authorization tokens
-
If the client side is doing complex computing how will you optimize so that the result can be reused and optimize the performance
-
How will you handle when the vulnerability arises in the third-party library used in your project
-
If a component is rerendering unnecessarily what will you do to find and solve the issues
-
If the page is loading slowly what will be done to handle the performance issue
-
If a page How will you figure out the problem in a code and debug
-
it needs to be built and it should be responsive what is your approach
-
What is the use of the callback function given to the state
-
What are the states of Promise? Explain?
-
What is SSR (Server Side Rendering) in React?
-
What is the use of it?
-
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.
-
What is the Pure component?
-
How to pass data from the child component to the parent component?
-
Could you explain one practical example where you have created HOC(Higher Order Components)?
-
What is the difference between Virtual DOM and Real DOM?
-
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?
-
Redux: Why is it important to use? What does it solve?
-
How have you handled API calls in your application?
-
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.
-
Have you used Context API? Could you explain the difference between Context API and Redux?
-
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?
-
Can you explain let and var for hoisting? How will they differ?
-
Explain the difference between functional and class components.
-
Explain the difference between props and states.
-
Explain the difference between Stateless and stateful components.
-
Explain the difference between controlled and uncontrolled components.
-
Explain About React. lazy and also explain the what is the use of suspense in the react lazyloading
Some Important Questions And Answers 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: Blueprint for creating objects with shared properties and methods.
- Arrow Functions: Concise syntax for function expressions with lexical
this
. - Variables (
let
,const
,var
):let
for reassignable variables,const
for constants,var
(older) with functional scope. - Array Methods like
map()
: Creates a new array by applying a function to each element. - Destructuring: Extracts values from arrays or objects into variables.
- Modules: Organizes code into reusable and maintainable files.
- Ternary Operator: Shortens
if-else
statements into a concise one-liner. - Spread Operator: Expands elements of an array or properties of an object.
4. What is the difference between the Arrow function and Normal functions in Reactjs?
1. Syntax changes
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 argument 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 the case of a regular function:
let myFunc = { showArgs() { console.log(arguments); } }; myFunc.showArgs(1, 2, 3, 4);
In the 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); }, }
Regular Function
thisInRegular() { console.log("My name is " + this.name); } }; 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. Before 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 most simply. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.
Benefits of Promises
- Improves Code Readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- 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 been fulfilled or rejected
var promise = new Promise(function(resolve, reject) { resolve(1 * 2 } 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 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 in class 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 a 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 a use case with the State of the component and rendering the UI based on the Component State, using the 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 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 faster than class components, | The class Component is low compared to the 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.
what are 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 Components
- 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 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 are 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 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. As promising as it sounds, new hooks have 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:
- class 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, and 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 the child component to the parent component?
Following are the steps to pass data from the child component to the parent component:
- In the parent component, create a callback function. This callback function will retrieve the data from the child component.
- Pass the callback function to the child as a prop from the parent component.
- 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. 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={ha ndleSubmit}> <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 needs 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 the 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();
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 a 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
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"; 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"));
14. 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.
15. Explain React Router. Can you explain the 3 React Router primary categories in detail?
- 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 blog 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: the home component, the about a component, and the 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 shown component that renders some UI when its path matches the current URL.
-
Link: The link component is used to create links to different routes and implement navigation around the application. It works like HTML
Now, you can click on the links and navigate to different components. React Router keeps your application UI in sync with the URL.
16. 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 apps and 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) => {}; 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 the 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 to 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 }) ); }; };
17.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 values that 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.
18. 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 that 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.
19. 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 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.
- Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
- Then the difference between the previous DOM representation and the new one is calculated.
5. Once the calculations are done, the real DOM will be updated with only the things that have changed.
-
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. Create a new DOM if the element updates. |
3. Updates the JSX if the element updates. |
4. DOM manipulation is very expensive. |
4. DOM manipulation is very easy. |
5. Too much memory wastage. |
5. No memory wastage. |
20. Explain 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 the constants in Redux?
-
Show using code how constants can be used in Redux.
-
What are the reducers in Redux`s architecture? Show an example of 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 that we should never do inside a reducer?
-
How can the addition of multiple middleware 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?
-
What is the equivalent of the following using React.createElement?