# React interview questions 1. **What are the advantages of React?** Below are the list of main advantages of React, 1. Increases the application's performance with *Virtual DOM*. 2. JSX makes code easy to read and write. 3. It renders both on client and server side (*SSR*). 4. Easy to integrate with frameworks (Angular, Backbone) since it is only a view library. 5. Easy to write unit and integration tests with tools such as Jest. 53. **What are the limitations of React?** Apart from the advantages, there are few limitations of React too, 1. React is just a view library, not a full framework. 2. There is a learning curve for beginners who are new to web development. 3. Integrating React into a traditional MVC framework requires some additional configuration. 4. The code complexity increases with inline templating and JSX. 5. Too many smaller components leading to over engineering or boilerplate. 1. **Do browsers understand JSX code?** No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel. 286. Is it possible to use react without JSX? Yes, JSX is not mandatory for using React. Actually it is convenient when you don’t want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling `React.createElement(component, props, ...children)`. For example, let us take a greeting example with JSX, ```javascript= const Greeting =() => { return <div>Hello {this.props.message}</div>; } } ReactDOM.render( <Greeting message="World" />, document.getElementById('root') ); ``` You can write the same code without JSX as below, ```javascript= const Greeting =() => { return React.createElement('div', null, `Hello ${this.props.message}`); } ReactDOM.render( React.createElement(Greeting, {message: 'World'}, null), document.getElementById('root') ); ``` 312. **Describe about data flow in react?** React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding. 1. **What is the difference between state and props?** Both *props* and *state* are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function. 12. **What is the purpose of callback function as an argument of `setState()`?** 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. ```javascript= setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered')) ``` 82. **Why we need to pass a function to setState()?** 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. ```javascript= // assuming state.count === 0 setState({ count: state.count + 1 }) setState({ count: state.count + 1 }) setState({ count: state.count + 1 }) // state.count === 1, not 3 ``` If we pass a function to `setState()`, the count gets incremented correctly. ```javascript= setState((prevState, props) => ({ count: prevState.count + props.increment })) // state.count === 3 as expected ``` 306. **Why do we use array destructuring (square brackets notation) in `useState`?** When we declare a state variable with `useState`, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead. For example, the array index access would look as follows: ```javascript= var userStateVariable = useState('userProfile'); // Returns an array pair var user = userStateVariable[0]; // Access first item var setUser = userStateVariable[1]; // Access second item ``` Whereas with array destructuring the variables can be accessed as follows: ```javascript= const [user, setUser] = useState('userProfile'); ``` 332. **What is the difference between useState and useRef hook?** 1. useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes. Essentially, useRef is like a “box” that can hold a mutable value in its (.current) property. 2. useState allows us to update the state inside components. While useRef allows refrencing DOM elements. 16. **What are synthetic events in React?** `SyntheticEvent` is a cross-browser wrapper around the browser's native event. Its API is same as the browser's native event, including `stopPropagation()` and `preventDefault()`, except the events work identically across all browsers. [More](https://reactjs.org/docs/events.html) 18. **What is "key" prop and what is the benefit of using it in arrays of elements?** 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*: ```jsx= const todoItems = todos.map((todo) => <li key={todo.id}> {todo.text} </li> ) ``` When you don't have stable IDs for rendered items, you may use the item *index* as a *key* as a last resort: ```jsx= const todoItems = todos.map((todo, index) => <li key={index}> {todo.text} </li> ) ``` **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. 313. **What is react scripts?** The `react-scripts` package is a set of scripts from the create-react-app starter pack which helps you kick off projects without configuring. The `react-scripts start` command sets up the development environment and starts a server, as well as hot module reloading. 96. **What is the difference between React and ReactDOM?** The `react` package contains `React.createElement()`, `React.Component`, `React.Children`, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The `react-dom` package contains `ReactDOM.render()`, and in `react-dom/server` we have *server-side rendering* support with `ReactDOMServer.renderToString()` and `ReactDOMServer.renderToStaticMarkup()`. 24. **What is Virtual DOM?** The *Virtual DOM* (VDOM) is an in-memory representation of *Real DOM*. The representation of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called *reconciliation*. 25. **How Virtual DOM works?** The *Virtual DOM* works in three simple steps. 1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation. ![vdom](https://raw.githubusercontent.com/minhtan7/reactjs-interview-questions/master/images/vdom1.png) 2. Then the difference between the previous DOM representation and the new one is calculated. ![vdom2](https://raw.githubusercontent.com/minhtan7/reactjs-interview-questions/master/images/vdom2.png) 3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed. ![vdom3](https://raw.githubusercontent.com/minhtan7/reactjs-interview-questions/master/images/vdom3.png) 298. What is the difference between Real DOM and Virtual DOM? Below are the main differences between Real DOM and Virtual DOM, | Real DOM | Virtual DOM | | ----- | ------- | | Updates are slow | Updates are fast | | DOM manipulation is very expensive. | DOM manipulation is very easy | | You can update HTML directly. | You Can’t directly update HTML | | It causes too much of memory wastage | There is no memory wastage| | Creates a new DOM if element updates | It updates the JSX if element update| 29. **What are controlled components**? A component that controls the input elements within the forms on subsequent user input is called **Controlled Component**, i.e, every state mutation will have an associated handler function. For example, to write all the names in uppercase letters, we use handleChange as below, ```javascript= handleChange(event) { setState({value: event.target.value.toUpperCase()}) } ``` 30. **What are uncontrolled components?** The **Uncontrolled Components** are the ones that store their 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. In the below UserProfile component, the `name` input is accessed using ref. ```jsx harmony function UserProfile(){ const inp = React.createRef() const handleSubmit= (event) => { alert('A name was submitted: ' + inp.current.value) event.preventDefault() } return ( <form onSubmit={handleSubmit}> <label> {'Name:'} <input type="text" ref={inp} /> </label> <input type="submit" value="Submit" /> </form> ); } ``` In most cases, it's recommend to use controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself. 45. **Why React uses `className` over `class` attribute?** `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`. Pass a string as the `className` prop. ```jsx harmony render() { return <span className={'menu navigation-menu'}>{'Menu'}</span> } ``` In React 16, there is a breaking change in the changelog compared to React 15: <small>[Read more](https://www.geeksforgeeks.org/why-react-uses-classname-over-class-attribute/)</small> Web components (custom elements) now use native property names. Eg: class instead of className. 49. **What are stateless components?** 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. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the `this` keyword altogether. 50. **What are stateful components?** 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`. ```javascript= class App extends Component { constructor(props) { super(props) this.state = { count: 0 } } render() { // ... } } ``` **React 16.8 Update:** Hooks let you use state and other React features without writing classes. *The Equivalent Functional Component* ```javascript= import React, {useState} from 'react'; const App = (props) => { const [count, setCount] = useState(0); return ( // JSX ) } ``` 61. **How to use styles in React?** The `style` attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes. ```jsx harmony const divStyle = { color: 'blue', backgroundImage: 'url(' + imgUrl + ')' }; function HelloWorldComponent() { return <div style={divStyle}>Hello World!</div> } ``` Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. `node.style.backgroundImage`). 68. **Why we need to be careful when spreading props on DOM elements?** When we *spread props* we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with `...rest` operator, so it will add only required props. For example, ```javascript= const ComponentA = () => <ComponentB isDisplay={true} className={'componentStyle'} /> const ComponentB = ({ isDisplay, ...domProps }) => <div {...domProps}>{'ComponentB'}</div> ``` 83. **What is strict mode in React?** `React.StrictMode` is a useful component for highlighting potential problems in an application. Just like `<Fragment>`, `<StrictMode>` does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for *development mode* only. ```jsx harmony import React from 'react' function ExampleApplication() { return ( <div> <Header /> <React.StrictMode> <div> <ComponentOne /> <ComponentTwo /> </div> </React.StrictMode> <Header /> </div> ) } ``` In the example above, the *strict mode* checks apply to `<ComponentOne>` and `<ComponentTwo>` components only. `<StrictMode>` also help you spot side-effect by making them a little more [deterministic](https://en.wikipedia.org/wiki/Deterministic_algorithm). This is done by intentionally double-invoking the following functions: - Function component bodies - State updater functions (the first argument to setState) - Functions passed to useState, useMemo, or useReducer Read more [here](https://reactjs.org/docs/strict-mode.html) 87. **Why should component names start with capital letter?** 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 an unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter. #### What are the exceptions on React component naming? The component names should start with an uppercase letter but there are few exceptions to 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, ```jsx harmony render() { return ( <obj.component/> // `React.createElement(obj.component)` ) } ``` 303. **How to fetch data with React Hooks?** The effect hook called `useEffect` is used to fetch the data with axios from the API and to set the data in the local state of the component with the state hook’s update function. Let's take an example in which it fetches list of react articles from the API ```javascript= import React, { useState, useEffect } from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({ hits: [] }); useEffect(() => { (async () => { const result = await axios( 'http://hn.algolia.com/api/v1/search?query=react', ); setData(result.data); })() }, []); return ( <ul> {data.hits.map(item => ( <li key={item.objectID}> <a href={item.url}>{item.title}</a> </li> ))} </ul> ); } export default App; ``` Remember we provided an empty array as second argument to the effect hook to avoid activating it on component updates but only on mounting of the component. i.e, It fetches only on component mount. 324. **What are the benefits of using typescript with reactjs?** Below are some of the benefits of using typescript with Reactjs, 1. It is possible to use latest JavaScript features 2. Use of interfaces for complex type definitions 3. IDEs such as VS Code was made for TypeScript 4. Avoid bugs with the ease of readability and Validation 325. **How do you make sure that user remains authenticated on page refresh while using Context API State Management?** When a user logs in and reload, to persist the state generally we add the load user action in the useEffect hooks in the main App.js. While using Redux, loadUser action can be easily accessed. **App.js** ```javascript= import {loadUser} from '../actions/auth'; store.dispatch(loadUser()); ``` But while using **Context API**, to access context in App.js, wrap the AuthState in index.js so that App.js can access the auth context. Now whenever the page reloads, no matter what route you are on, the user will be authenticated as **loadUser** action will be triggered on each re-render. **index.js** ```javascript= import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import AuthState from './context/auth/AuthState' ReactDOM.render( <React.StrictMode> <AuthState> <App /> </AuthState> </React.StrictMode>, document.getElementById('root') ); ``` **App.js** ```javascript= const authContext = useContext(AuthContext); const { loadUser } = authContext; useEffect(() => { loadUser(); },[]) ``` **loadUser** ```javascript= const loadUser = async () => { const token = sessionStorage.getItem('token'); if(!token){ dispatch({ type: ERROR }) } setAuthToken(token); try { const res = await axios('/api/auth'); dispatch({ type: USER_LOADED, payload: res.data.data }) } catch (err) { console.error(err); } } ``` 267. **What are the conditions to safely use the index as a key?** There are three conditions to make sure, it is safe use the index as a key. 1. The list and items are static– they are not computed and do not change 2. The items in the list have no ids 3. The list is never reordered or filtered. 268. **Should keys be globally unique?** The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays. For example, the below `Book` component uses two arrays with different arrays, ```javascript= function Book(props) { const index = ( <ul> {props.pages.map((page) => <li key={page.id}> {page.title} </li> )} </ul> ); const content = props.pages.map((page) => <div key={page.id}> <h3>{page.title}</h3> <p>{page.content}</p> <p>{page.pageNumber}</p> </div> ); return ( <div> {index} <hr /> {content} </div> ); } ``` 330. **What is prop drilling?** Prop Drilling is the process by which you pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around.