Table of contents
- What is React?
- Compare React with other frameworks.
- Is React a library or a framework?
- Which React frameworks do you know?
- Do you think we should learn frameworks also?
- What is SPA ?
- What are components?
- What is JSX?
- What do you mean by declarative syntax?
- What are the rules of JSX and how does it differ from HTML?
- How to apply styles to React components?
- How to conditionally apply class attributes?
- What are props in React?
- Why you can't update props in React?
- Is there one-way or two-way data binding (or data flow) in React?
- What is state in React?
- What is the difference between state and props?
- What is Lifting State Up in React?
- What is Derived state?
- What is children prop?
- What is Virtual DOM?
- How Virtual DOM works?
- What is the difference between Shadow DOM and Virtual DOM?
- Controlled components/elements?
- Why should we not update the state directly?
- What is the purpose of callback function as an argument of setState()?
- What is the difference between HTML and React event handling?
- What are synthetic events in React?
- What are inline conditional expressions?
- What is "key" prop and what is the benefit of using it in arrays of elements?
- What is the use of refs?
- What are forward refs?
- What are controlled & uncontroleld components? Which one to prefer?
- What are the different phases of component lifecycle?
- What are Pure Components?
What is React?
React is a library for web and native user interfaces.
Compare React with other frameworks.
React is a library. Angular and Vue are frameworks. Personally I think, all frameworks are good and depend on person to person which is better suited for their needs. With Angular, you get all the things, like router, typescript etc. With React, you get only React. If you want to develop web apps, add react-dom. If you want to develop native apps, you add react-native. You want to use router, add react-router. Vue is a combination of both React and Angular. It is a framework, but instead of searching for dependency from vast packages, Vue suggests some dependencies like vue-router, Pinea, which are developed by them.
Is React a library or a framework?
React is a library and not a framework. A library is defined as a group of related functions and classes that perform unique operations. Like, a Math library, which has many functions and classes such as min, max, floor, ceil, etc that perform some actions related to numbers.
Which React frameworks do you know?
There are number of frameworks based on React, like Next js, Remix, Gatsby but Remix is by far my favourite framework. In fact, I am using Remix since it was made open-source and public.
Do you think we should learn frameworks also?
Yes. After the release of hooks, the React team advised using hooks with functional components instead of a class-based approach. Now, I don't see anyone using class based approach. The React team now advises to use React Framework.
What is SPA ?
SPA means single-page-application. In single page applications, when a webpage is requested by the browser, the downloaded page includes minimal HTML, JS; afterwards which there are no full page requests. Even though the SPA is new term for many developers, we were using SPA since many years. Web applications like Gmail, Yahoo mail were SPA.
What are components?
Components are the building blocks of creating User Interfaces(UI) in React. They are reusable piece of code. We build complex UIs by building and combining multiple components. For examples small components like buttons, inputs they combine to make bigger components like modal, data-table which combine to make header, footer, main which at the end makes a page.
What is JSX?
Documentation: JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. We describe how components look like and how they work using a declarative syntax called JSX. JSX and React are two separate things. They’re often used together, but you can use them independently of each other. JSX is a syntax extension, while React is a JavaScript library.
What do you mean by declarative syntax?
Telling React what a component should look like, based on the current state/data.
What are the rules of JSX and how does it differ from HTML?
How to apply styles to React components?
React doesn't actually cares how the components are styled as it is a JavaScript library not a framework. So, we can use Inline stying, external CSS or SCSS files, CSS modules, Styled Components, or even Tailwind CSS.
import { styled } from "styled-components";
import "./pizza.css"; // CSS file import
import styles from "./styles.module.css"; // CSS module
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: #bf4f74;
`;
function Pizza({ pizzaObj }) {
return (
<li className={`pizza ${pizzaObj.soldOut ? "sold-out" : ""}`}>
{/* styled components */}
<Title>Pizza</Title>
{/* Inline style */}
<h2 style={{ color: "red", fontSize: "24px" }}>{pizzaObj.name}</h2>
{/* style class name from CSS file imported at top */}
<span className="pizza-description">{pizzaObj.description}</span>
{/* style module from CSS module */}
<span className={styles.price}>{pizzaObj.price}</span>
{/* Tailwind CSS */}
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Buy
</button>
</li>
);
}
How to conditionally apply class attributes?
If I want to add a class based on some condition, I use curly bracket to use template literal (backtick ` . . . `). Write static className if required. To write the condition inside template literal use dollar sign curly brackets(${}). Add condition that returns a string using ternary operator. Example as below.
function Pizza({ pizzaObj }) {
return (
<li className={`pizza ${pizzaObj.soldOut ? "sold-out" : ""}`}>
{pizzaObj.name}
</li>
);
}
What are props in React?
Props are used to pass data from Parent to Child component. React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
Why you can't update props in React?
Documentation: Props are immutable—a term from computer science meaning “unchangeable”. When a component needs to change its props (for example, in response to a user interaction or new data), it will have to “ask” its parent component to pass it different props—a new object!.Its old props will then be cast aside, and eventually the JavaScript engine will reclaim the memory taken by them.
My understanding: Props is just an object afterall. If you change the props object in child component, you would also affect the parent component, because that's just how objects work in JavaScript. So when you copy the object and mutate the copy, the original object will also be mutated. Now, if you change an object that is located, outside of the child component function, that function has then created a so-called side effect. So in general, a side effect happens whenever you change some data that's located outside of the current function. React, however, is all abut pure functions, so functions without side effects, at least it's about component's data. So components have to be pure in terms of their props ans state, because, this allows React to optimise your application and it avoids some strange bugs that can appear when you manipulate the external data.
Is there one-way or two-way data binding (or data flow) in React?
Pluralsight: React uses one-way data binding. To explain this, data flows from parent to the child. Originally React was created based on frustrations with existing web frameworks that used MVC and two-way data binding.
With smaller components, there is not much difference. But when the application scales up, that is more components are created, MVC impacts the performance. When we scale the React app, all components update the virtual DOM, and in single merge step, Real DOM is updated in one pass.
What is state in React?
State is a data that a component can hold over time. State is the information that needs to remember throughout the app’s lifecycle. You can call this component's memory. Updating the state causes re-render of the component.
What is the difference between state and props?
What is Lifting State Up in React?
Lifting state up simply means to place a state in a common component that is a parent of both components that need the piece of state in question. And now giving both these component access to the state is as easy as passing the state down using props. If the children component wants to update the props, we cannot mutate the prop directly. So we use setter function as prop that will update the state of the Parent and therefore update the prop passing to the chil component. This is called Child-to-Parent communication (inverse data flow): child updating parent state (data "flowing up")
What is Derived state?
Derived state is the state that is computed from an existing piece of state of from props.
What is children
prop?
The children prop allow us to pas JSX into an component (besides regular props). It is really helpful for generic components that don't know their content before being used (e.g. modal)
What is Virtual DOM?
The Virtual DOM is a lightweight copy of the real DOM that React uses to optimize updates by minimizing direct DOM manipulation.
How Virtual DOM works?
React creates a virtual copy of the DOM, compares it with the previous version (diffing), and updates only the changed parts in the real DOM (reconciliation).
What is the difference between Shadow DOM and Virtual DOM?
Virtual DOM is used by libraries like React to optimize DOM updates. Shadow DOM is a browser feature for encapsulating styles and markup in web components.
Controlled components/elements?
In practice, “controlled” and “uncontrolled” aren’t strict technical terms—each component usually has some mix of both local state and props. However, this is a useful way to talk about how components are designed and what capabilities they offer.
Why should we not update the state directly?
Directly updating the state can lead to unpredictable UI behaviour and prevent React from properly re-rendering components, as it does not trigger a re-render.
What is the purpose of callback function as an argument of setState()?
The callback function ensures that you execute code after the state has been updated and the component has re-rendered, providing access to the latest state.
What is the difference between HTML and React event handling?
In HTML, event handling is done using lowercase event names like onclick
. In React, events are handled using camelCase like onClick
. In React, handleClick
is passed as a function reference, while in HTML, it's a string that gets evaluated. React's virtual DOM optimizes event handling across browsers.
In HTML:
<button onclick="handleClick()">Click</button>
In React:
<button onClick={handleClick}>Click</button>
What are synthetic events in React?
Synthetic events in React are cross-browser wrappers around native events. They normalize event properties and methods to provide consistent behavior across different browsers, allowing developers to write event handling code without worrying about browser-specific differences.
Here's a simple example of a synthetic event in React:
function MyComponent() {
const handleClick = (event) => {
console.log(event); // This is a SyntheticEvent
};
return <button onClick={handleClick}>Click me</button>;
}
In this example, event
is a synthetic event that React provides, which behaves consistently across browsers.
What are inline conditional expressions?
Inline conditional expressions in React allow you to conditionally render elements within JSX using JavaScript expressions. The common methods include the ternary operator and logical AND operator.
{isLoggedIn ? <UserGreeting /> : <GuestGreeting />}
{isLoggedIn && <UserGreeting />}
What is "key" prop and what is the benefit of using it in arrays of elements?
The "key" prop in React is a unique identifier assigned to each element in a list. It helps React identify which items have changed, been added, or removed, allowing for efficient updates and re-renders.
Benefits of using the "key" prop:
Performance: It improves rendering performance by minimizing unnecessary re-renders of unchanged elements.
Stability: It maintains the component's state across updates, preventing issues when elements are reordered or removed.
What is the use of refs?
Refs in React are used to access and interact with DOM elements directly. They provide a way to manage focus, trigger animations, or retrieve values without re-rendering the component.
Common uses of refs:
Accessing DOM elements: For example, getting the value of an input field or controlling focus.
Integrating with third-party libraries: To manage components that require direct DOM manipulation.
Storing mutable values: To track values that don’t trigger re-renders, like timers or previous state values.
Here are examples of using refs in functional components with hooks:
- Accessing a DOM element:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
- Integrating with a third-party library:
import React, { useRef, useEffect } from 'react';
import Chart from 'chart.js';
function ChartComponent() {
const canvasRef = useRef(null);
useEffect(() => {
const ctx = canvasRef.current.getContext('2d');
new Chart(ctx, {
// Chart configuration
});
}, []);
return <canvas ref={canvasRef} />;
}
- Storing mutable values:
import React, { useRef, useEffect } from 'react';
function TimerComponent() {
const timerRef = useRef(null); // How to create refs?
useEffect(() => {
timerRef.current = setInterval(() => {
console.log('Timer tick');
}, 1000);
return () => clearInterval(timerRef.current);
}, []);
return <div>Check the console for timer ticks!</div>;
}
What are forward refs?
Forward refs in React allow a parent component to pass a ref
directly to a child component's DOM element. It is implemented using React.forwardRef
.
import React, { forwardRef } from 'react';
const InputComponent = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
function ParentComponent() {
const inputRef = React.useRef(null);
return (
<div>
<InputComponent ref={inputRef} placeholder="Type here" />
</div>
);
}
What are controlled & uncontroleld components? Which one to prefer?
For controlled components, you manage the input's value with state.
For uncontrolled components, the
useRef
hook is used to access the DOM directly.
Both are used, but controlled components are preferred for better control and predictable behavior, especially in forms. Uncontrolled components are used for quick or simple cases where React state management isn't needed
A controlled component is a form element where the React state manages its value. The value
of the input is bound to state, and updates are handled via onChange
.
import React, { useState } from 'react';
function ControlledInput() {
const [value, setValue] = useState<string>('');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
};
return (
<input
value={value}
onChange={handleChange}
placeholder="Controlled"
/>
);
}
import React, { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef<HTMLInputElement>(null);
const handleSubmit = () => {
if (inputRef.current) {
console.log(inputRef.current.value);
}
};
return (
<>
<input ref={inputRef} placeholder="Uncontrolled" />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
What are the different phases of component lifecycle?
In modern React, the concept of lifecycle phases still applies, though managed differently compared to class components. Here’s a breakdown:
1. Mounting Phase
Occurs when a component is added to the DOM. Equivalent to componentDidMount
in class components.
Example Hook:
useEffect
(with an empty dependency array[]
).Usage:
useEffect(() => { // Runs after the component mounts }, []);
2. Updating Phase
Occurs when the component re-renders due to state or prop changes.
Example Hook:
useEffect
(with dependencies in the array).Usage:
codeuseEffect(() => { // Runs when specific state or props change }, [dependency]);
3. Unmounting Phase
Occurs when a component is removed from the DOM. Equivalent to componentWillUnmount
in class components.
Example Hook: Cleanup function in
useEffect
.Usage:
codeuseEffect(() => { return () => { // Cleanup logic }; }, []);
4. Error Handling Phase (optional)
Handles errors during rendering or lifecycle methods.
- Usage: Use
Error Boundary
withcomponentDidCatch
in class components or create custom hooks for error tracking.
Example of All Phases in Functional Components:
import React, { useState, useEffect } from 'react';
function LifecycleExample() {
const [count, setCount] = useState(0);
// Mounting: Runs once when the component mounts
useEffect(() => {
console.log('Component mounted');
// Unmounting: Cleanup
return () => {
console.log('Component unmounted');
};
}, []);
// Updating: Runs when count changes
useEffect(() => {
console.log('Count updated:', count);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default LifecycleExample;
What are Pure Components?
PureComponent skips re-renders for same props and state. Class components are still supported by React, but I don’t recommend using them in new code. Instead wrap the component in memo. Following is the example where we can transform from Class based pure components to function based component using memo
// Class based approach
import { PureComponent, useState } from 'react';
class Greeting extends PureComponent {
render() {
console.log("Greeting was rendered at", new Date().toLocaleTimeString());
return <h3>Hello {this.props.name}</h3>;
}
}
// Function based component
import { memo, useState } from 'react';
const Greeting = memo(function Greeting({ name }) {
console.log("Greeting was rendered at", new Date().toLocaleTimeString());
return <h3>Hello {name}</h3>;
});
What are Higher-Order components?
I would not recommend to use HOC in modern React. It is
What is children prop?
How to write comments in React?
Is lazy function supports named exports?
Why React uses className over class attribute?
What are fragments?
Why fragments are better than container divs?
What are stateless components?
What are stateful components?
What is the purpose of render method of react-dom?
How to use InnerHtml in React?
How to use styles in React?
How events are different in React?
What is the impact of indexes as keys?
How do you memoize a component?
How to enable production mode in React?
What is the difference between React and ReactDOM?
Why ReactDOM is separated from React?
How to use React label element?
How to combine multiple inline style objects?
How to re-render the view when the browser is resized?
How to pretty print JSON with React?
How to focus an input element on page load?
How to programmatically trigger click event in React?
What is React Router?
What is React-Intl?
What are the main features of React Intl?
Can I import an SVG file as react component?
How to pass numbers to React component?
What are hooks? Explain React Hooks.
What are Custom Hooks?
What rules need to be followed for hooks?
Give an example on How to use context?
What is the purpose of default value in context?
How do you print falsy values in JSX?
How to fetch data with React Hooks?
What are React Server components?
What is prop drilling?
What is strict mode in React?
Strict mode lets you find common bugs in your components early during development.
What is redux?
What would you do if your React application is rendering slowly?