- What is the React Virtual DOM? How is it different from the real DOM & Shadow DOM? Virtual DOM is a concept where a virtual representation of the real DOM is kept inside the memory and is synced with the actual DOM by a library such as ReactDOM only when necessary.
The Virtual DOM is an object that represents the real DOM in the memory. Since DOM updates are an integral part of any web app but are the costliest operation in frontend development, the Virtual DOM is utilized to check for parts of the app that need to be updated & update only those parts, thus significantly boosting performance.
The Virtual DOM is a completely different concept from the real DOM and shadow DOM. The real DOM is the actual representation of the HTML document in a tree-like structure that browsers use to track the contents of a web page, and the Shadow DOM is a programming practice that allows developers to create isolated reusable components for web applications.
If you want to dive deeper into the differences between Virtual DOM, real DOM & the Shadow DOM, check out this article
- What are the 2 types of components in React? Where should we use them? There are 2 types of components in React:
Class Components
Functional Components
Previously, class components were the only way to create components with any functionality in React, with the functional components being used only as presentational components and often being referred to as "dumb" components.
But, with the release of React 16.8 and the introduction of React Hooks, functional components can now have state & lifecycle methods, making them the preferred way to create components in React.
Functional components are much faster than class components with less overhead & boilerplate code, so it's recommended to use functional components wherever possible. However some of the lifecycle methods are still available only in class components, so you might need to use class components in some niche cases like creating your custom error boundaries (eg: using the componentDidCatch lifecycle method in class components).
- Why do we need keys in React? Can we use keys without lists in React? keys
Keys in React are used to identify unique Virtual DOM Elements with their corresponding data driving the UI. Using keys helps React optimize rendering by recycling existing DOM elements.
Keys help React identify which items have changed, are added, or are removed, enabling it to reuse already existing DOM elements, thus providing a performance boost.
For example:
const Todos = ({ todos }) => {
return (
{todos.map((todo) => (
))}
);
};
This would cause new DOM Elements to be created every time todos change, but adding the key prop (ie:
Keys can be used with any element in React & does not necessarily need to be used with lists, but it's most commonly used with lists to optimize rendering. Some non-standard (& non-recommended) use cases of keys include using them to force the re-rendering of components like the example below:
const TimeNow = () => {
const [key, setKey] = useState(0);
useEffect(() => {
const interval = setInterval(() => setKey((prevKey) => prevKey + 1), 1000);
return () => clearInterval(interval);
}, []);
return
{new Date()};};
As mentioned, code like this should definitely be avoided & you are better off using the state to store the time instead of the key to force re-rendering. Using keys to force re-rendering is an anti-pattern & can lead to severe performance issues unless you know exactly what you are doing.
- Difference between controlled and uncontrolled input in React Controlled components rely on the React state to manage the form data, while uncontrolled components use the DOM itself to handle form data.
In most cases, controlled components are preferred because they provide a single source of truth for the form data, making it easier to manage, validate, and submit the form data.
const ControlledInputForm = () => {
const [value, setValue] = useState("");
const handleChange = (e) => setValue(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
console.log(value);
};
return (
Submit
);
};
const UncontrolledInputForm = () => {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log(inputRef.current.value);
};
return (
Submit
);
};
- Why do we need to transpile JSX code? Unless you hurt your head, you are NOT using React like this:
import { createElement } from "react";
const Greeting = ({ name }) => {
return createElement("h1", { className: "greeting" }, "Hello");
};
Yet, this is what the browser reads - it is simply unable to understand the JSX syntax commonly used to write React components.
Thus we are required to use tools like Babel to transpile JSX to JavaScript so that the browser can execute it. So when you write the following code:
const Greeting = ({ name }) =>
Hello
;It's transpiled to the former code snippet so that the browser can interpret it & render the component.
- How does JSX prevent injection attacks? GIFinjection
Since JSX renders content as text, any element in user input is not treated as HTML, just as plain text. For example, the following script tag would be rendered as text and not executed:
const MyComponent = () => {
const content = "alert('XSS')";
return
};
NOTE: You can override this behavior by using dangerouslySetInnerHTML but it's not recommended unless you are absolutely sure about the source of the input (& would strongly suggest sanitizing the content before injecting it).
const MyComponent = () => {
const content = "alert('XSS')";
return
};
- How can we add styling to React components? CSS Files Using CSS files is one of the most common ways to style React components. It allows for the use of all CSS features and is set up by default with the Create React App.
/* Button.css */
.button {
background-color: blue;
color: white;
}
// Button.tsx
import "./Button.css";
const Button = () => {
return Click me;
};
Inline CSS
Styling React elements using inline CSS allows styles to be completely scoped to an element. However, certain styling features are not available with inline styles. For example, the styling of pseudo-classes like :hover.
const Button = () => {
return (
Click me
);
};
Top comments (0)