React interview questions answered and explained #1
Tags: react, webdev
Published: 2021-11-02 17:41:16

## Video 
If you'd prefer a video with animated examples, you can check out the video that I made on this topic [on my YouTube channel:](https://www.youtube.com/channel/UCicOwFWkuMX0ddFaKCc_E5Q)

{% youtube 8RBkkyOLWPc %}
### What is React?
React is an open-source frontend JavaScript library which is used for building user interfaces especially for single page applications. It uses a component based approach to create reusable UI pieces. It was developed at facebook, and published to open-source in 2013.

### What are the major features of React?
React uses a **virtual DOM** to track changes in the document object model, and only updates the changed parts in the real DOM. It supports both client-side and server-side rendering and it uses unidirectional data flow with props. We can create composable or reusable UI elements with it.
### What is JSX?
The acronym itself stands for JavaScript XML. It  is an extension to the JavaScript language syntax. It has a similar appearance like HTML, we can use html tags in it, and we can also use javascript expressions, and read javascript variables, if we put them into curly braces. JSX provides a good way to structure component rendering. We typically write React components using JSX, however it is not necessary at all. You can write React components using pure JavaScript.
React component without jsx, only javascript:
![React component without jsx, only javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brg4w8foa01xfcv4uuzd.png)
React component with JSX:
![React component with JSX](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yfy4cii11cspninn96r6.png) 
### What is the difference between React Elements and Components?
An Element is a plain object describing DOM nodes or other components. They describe what you want to render in the browser. Elements can contain other Elements in their props. Creating a React element is cheap. After its creation, it is never mutated.
![React element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00c91mdpe981258pvswk.png)
A component on the other hand can be declared in several different ways. It can be an ES6 class with a render method or a simple function. Components can have an inner state unlike elements.In both cases it takes its input object called props and returns a JSX tree.
![React component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/40hkuqp5rm148mn8u5sq.png)
### What are the two main ways to create components?
We can create components using  functions or ES6 classes. If we choose to use the ES6 class approach we need to extend the Component or PureComponent classes provided by React.
![Class component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5j4j4nrgskgwag1ytz50.png) 
The other approach, which is getting more and more popular, is to create a component by using a function. We can create it with the function keyword or by creating a function expression, even with arrow functions.
![Functional component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8997c1ou55y4p04dxed7.png)
### When to use a Class Component over a Function Component?
The short answer is if you are using a fresh version of React, it is up to you. However before the release of version 16.8, if your component needed state or you wanted to do something in a specific life cycle of the component you had to use class based components. Hooks came with version 16.8 and they started to conquer the world at a fast pace. Now you can do everything using hooks, no need for class based components.
### What are Pure Components?
A React component is considered pure if it renders the same output for the same state and props. If we declare Pure components, React will only re-render the component when the state or the props change, which results in rendering and performance boost.

When using class based components we can create Pure components by extending the PureComponent class instead of the Component. This way React will implement the shouldComponentUpdate lifecycle method, and will do a shallow comparison of the props and state to determine if it should re-render.
![Pure component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vvdpz24h5mt4w8ydhdpa.png) 

As of today we can also create pure components using functional components. We can do so by wrapping our component into the Memo Higher Order Component provided by React.
![Pure functional component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vn7wlxf7mk8lb3j8pq3h.png)
### What is ‘state’ in React?
The state is private data of the component, which can change during its lifetime. If the state of the component changes the component re-renders.
While using class based components, state is represented by an object, and we can modify it with the setState method.
![State in class components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plpx75tnh6yaj28wdn0o.png)
In functional components we can use the useState Hook. It gives back 2 variables in an array, the first one is the stateful data and the second one is the setter for it. We can set the default state, by providing it in the useState function call.
![State in functional components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cmhe060ttan9dqp8h1q.png)
### What are props in React?
Props are input data to components, they can be primitive values or objects. They are unidirectional, which means props can only be passed down from parent to child. Props are passed to components on creation. We can provide them in JSX with a naming convention similar to HTML tag attributes. The child components receive all the provided props in the props object. In class based components we can reach them in this.props, in functional components they are passed as parameters, and we can extract them from there.
### 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 components. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.
![Passing props](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eygldxb4wty6eceanulq.png)
 
### Why should we not update the state directly using class based components?
By directly modifying the state, the component won’t be aware of the state change, and therefore won’t re-render. We should use the setState method instead, it schedules an update to a component's state object, and when the state changes the component will re-render.
🚨 Bad way of updating state, directly:
![Direct state update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zr61et4upwxdlw65xc0t.png)
✅ Setting state asynchronously:
![Setting state asynchronously](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2tfyrjpgm35olekg6u2.png)

### What is the purpose of the callback function in setState()?
The setState method is asynchronous, and the callback we provide in the arguments gets invoked when the state modification is done and the component gets re-rendered. It is used to make any post-modification changes, but we should use the componentDidUpdate lifecycle method instead.
![setState callback](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mqxns96is6vxnxi8lrz1.png) 

### What is the difference between HTML and React event handling?
In HTML, event names are all lowercase by convention, but in React, more precisely in JSX, event names are written in camelCase. Also note that the callback function is provided between doublequotes in HTML, but within curly braces in React.
`<button onclick="handleClick()"></button>`
In HTML, false can be returned to prevent default behavior, whereas in React preventDefault has to be called explicitly.
The last difference is that in HTML, the callback function has to be called, so you have to write the parentheses at the end, while in react we only pass the reference of the callback function.

Event handling in HTML:
![Event handling in HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3z4u771a50pv4y61fy6k.png)
Event handling in React:
![Event handling in React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsa88xqynq3o3g0gufkq.png)

### How to pass a parameter to an event handler?
You can pass an arrow function which returns the desired function call with the parameters provided.
![Passing param via an arrow function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zbh1myj9055sq4ae902.png) 
Or you can achieve the same behavior by calling the bind method on the passed callback function. The first value is the desired ‘this’ value, but starting from the second parameter, all further parameters will be passed to the function.
![Passing params with bind](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o69m2a881j98z14q7np9.png)
### What are synthetic events in React?
SyntheticEvent is a cross-browser wrapper around the browser's native event. It's API is the same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

### What are inline conditional expressions?
You can use inline conditional expressions to conditionally render React components or elements. You can use the ternary operator, which is a simplified if else statement that always returns a value. If you choose this approach, you need to provide the condition first, then after a question mark you have to provide what should be returned when the condition evaluates to true, and you can define what should be returned otherwise after a colon.
![Ternary operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxoipb5zutepbold0ltw.png)
If you don’t need the else branch of the if statement you can use the short circuit evaluation of the AND operator. If the left side of the AND operator evaluates to true it returns its left side operand. We can use this behavior if we want to render something when a specific condition is true and we don’t want to render anything if the condition evaluates to false.
![&& operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qm2uwzajsg25pb9olnd1.png) 

### What is the key prop and why do we use it?
When we render multiple components based on arrays, we use key props. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort. You shouldn’t use indexes for keys if the order of items may change.
List with keys:
![List with key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5aeimmc5ov0ii978htte.png)

## Where you can learn more from me?
I create education content covering web-development on several platforms, feel free to 👀 check them out.

I also create a newsletter where I share the week's or 2 week's educational content that I created. No bull💩 just educational content.

🔗 Links:
* 🍺 Support free education and [buy me a beer](https://ko-fi.com/adamnagy)
* 💬 Join our [community on Discord](https://discord.gg/GuxmcEgAjB)
* 📧 Newsletter [Subscribe here](https://www.getrevue.co/profile/dev_adamnagy)
* 🎥 YouTube [Javascript Academy](https://www.youtube.com/channel/UCicOwFWkuMX0ddFaKCc_E5Q)
* 🐦 Twitter: [@dev_adamnagy](https://twitter.com/dev_adamnagy)
* 📷 Instagram [@javascriptacademy](https://www.instagram.com/javascriptacademy/)