React interview questions answered and explained #1
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:
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 with JSX:
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. 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.
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. 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.
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.
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.
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. 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.
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.
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: ✅ Setting state asynchronously:
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.
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 React:
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. 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.
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. 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.
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:
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
- 💬 Join our community on Discord
- 📧 Newsletter Subscribe here
- 🎥 YouTube Javascript Academy
- 🐦 Twitter: @dev_adamnagy
- 📷 Instagram @javascriptacademy