React Flashcards
Learn React basics and advance concepts
What is React
?
React is a front-end and open-source JavaScript library which is useful in developing user interfaces specifically for applications with a single page. It is helpful in building complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.
The important features of React are:
- It supports server-side rendering.
- It will make use of the virtual DOM rather than real DOM (Data Object Model) as RealDOM manipulations are expensive.
- It follows unidirectional data binding or data flow.
- It uses reusable or composable UI components for developing the view.
What are the advantages
of using React?
-
Use of Virtual DOM to improve efficiency
: React uses virtual DOM to render the view. As the name suggests, virtual DOM is a virtual representation of the real DOM. Each time the data changes in a react app, a new virtual DOM gets created. Creating a virtual DOM is much faster than rendering the UI inside the browser. Therefore, with the use of virtual DOM, the efficiency of the app improves. -
Gentle learning curve
: React has a gentle learning curve when compared to frameworks like Angular. Anyone with little knowledge of javascript can start building web applications using React. -
SEO friendly
: React allows developers to develop engaging user interfaces that can be easily navigated in various search engines. It also allows server-side rendering, which boosts the SEO of an app. -
Reusable components
: React uses component-based architecture for developing applications. Components are independent and reusable bits of code. These components can be shared across various applications having similar functionality. The re-use of components increases the pace of development. -
Huge ecosystem of libraries to choose from
: React provides you with the freedom to choose the tools, libraries, and architecture for developing an application based on your requirement.
What are the limitations
of React?
The few limitations
of React are as given below:
- React is not a full-blown framework as it is only a library.
- The components of React are numerous and will take time to fully grasp the benefits of all.
- It might be difficult for beginner programmers to understand React.
- Coding might become complex as it will make use of inline templating and JSX.
What is useState()
in React?
The useState()
is a built-in React Hook that allows you for having state variables in functional components. It should be used when the DOM has something that is dynamically manipulating/controlling.
What are keys
in React?
A key
is a special string attribute that needs to be included when using lists of elements.
Importance of keys
-
-
Keys
help react identify which elements were added, changed or removed. -
Keys
should be given to array elements for providing a unique identity for each element. - Without
keys
, React does not understand the order or uniqueness of each element. - With
keys
, React has an idea of which particular element was deleted, edited, and added. -
Keys
are generally used for displaying a list of data coming from an API.
What is JSX
?
JSX
stands for JavaScript XML
. It allows us to write HTML inside JavaScript and place them in the DOM without using functions like appendChild( )
or createElement( )
.
What are the differences between functional
and class components
?
Before the introduction of Hooks
in React, functional components were called stateless components and were behind class components on a feature basis. After the introduction of Hooks
, functional components are equivalent to class components.
Although functional components are the new trend, the react team insists on keeping class components in React. Therefore, it is important to know how these components differ.
Declaration:
-
Functional components
are nothing but JavaScript functions and therefore can be declared using an arrow function or the function keyword -
Class components
, on the other hand, are declared using the ES6 class
Handling props
:
- In
functional components
, the handling of props is pretty straightforward. Any prop provided as an argument to a functional component can be directly used inside HTML elements -
this
keyword is used in the case ofclass components
Handling state
:
-
Functional components
use React hooks to handle state. It uses theuseState()
hook to set the state of a variable inside the component -
class component
usingthis.state
to add the variable
What is the virtual DOM
? How does react use the virtual DOM
to render the UI?
As stated by the react team, virtual DOM
is a concept where a virtual representation of the real DOM
is kept inside the memory and is synced with the real DOM by a library such as ReactDOM.
DOM manipulation is an integral part of any web application, but DOM manipulation is quite slow when compared to other operations in JavaScript. The efficiency of the application gets affected when several DOM manipulations are being done. Most JavaScript frameworks update the entire DOM even when a small part of the DOM changes.
For example, consider a list that is being rendered inside the DOM. If one of the items in the list changes, the entire list gets rendered again instead of just rendering the item that was changed/updated. This is called inefficient updating.
For every DOM object, there is a corresponding virtual DOM
object(copy
), which has the same properties. The main difference between the real DOM
object and the virtual DOM
object is that any changes in the virtual DOM object will not reflect on the screen directly. Consider a virtual DOM
object as a blueprint of the real DOM object. Whenever a JSX element gets rendered, every virtual DOM object gets updated.
What are the differences between controlled
and uncontrolled
components?
Controlled components
are form elements (like input
, textarea
, or select
) that are managed by React state. This means that the value of the form element is set and updated through React state.Controlled components
in React ensure that the form data is handled by the React state, providing a consistent and predictable way to manage user input.
Uncontrolled components
in React manage their own state internally rather than relying on React state. This approach is useful for simple forms where you don’t need to manipulate the input data through React state updates.Uncontrolled components
manage their state internally using DOM refs (useRef()
hook in functional components or React.createRef()
in class components) to access form element values directly.
What are props
in React?
The props
in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.
What are error boundaries
in React?
React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries
catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
What is React Hooks
?
Hooks
are functions that let us “hook into” React state and lifecycle features from a functional component.
React Hooks
cannot be used in class components. They let us write components without class.
There are 2 rules which must be followed while you code with Hooks
:
-
React Hooks
must be called only at the top level. It is not allowed to call them inside the nested functions, loops, or conditions. - It is allowed to call the
Hooks
only from the ReactFunction Components
.
React Hooks
are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each lifecycle of a component is having 3 phases which include mount
, unmount
, and update
. Along with that, components have properties and states. Hooks
will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.
Using Hook
, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now using the useState()
hook, we can keep the state in a functional component.
What is the use of useEffect
React Hooks?
The useEffect()
React Hook is used for performing the side effects
in functional components. With the help of useEffect()
, you will inform React that your component requires something to be done after rendering the component or after a state change. The function you have passed(can be referred to as “effect”) will be remembered by React and call afterwards the performance of DOM updates is over. Using this, we can perform various calculations such as data fetching, setting up document title, manipulating DOM directly, etc, that don’t target the output value. The useEffect()
hook will run by default after the first render and also after each update of the component. React will guarantee that the DOM will be updated by the time when the effect has run by it.
The useEffect()
React Hook will accept 2 arguments: useEffect(callback,[dependencies]);
Where the first argument callback represents the function having the logic of side-effect and it will be immediately executed after changes were being pushed to DOM. The second argument dependencies represent an optional array of dependencies. The useEffect()
will execute the callback only if there is a change in dependencies in between renderings.
Explain conditional rendering
in React.
Conditional rendering
refers to the dynamic output of user interface markups based on a condition state. It works in the same way as JavaScript conditions. Using conditional rendering
, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on.
There are different approaches for implementing conditional rendering in React. Some of them are:
- Using
if-else
conditional logic which is suitable for smaller as well as for medium-sized applications - Using
ternary operators
, which takes away some amount of complication from if-else statements - Using element variables, which will enable us to write cleaner code.
What is React Router
?
React Router
refers to the standard library used for routing in React. It permits us for building a single-page web application in React with navigation without even refreshing the page when the user navigates. It also allows to change the browser URL and will keep the user interface in sync with the URL. React Router
will make use of the component structure for calling the components, using which appropriate information can be shown. Since React is a component-based framework, it’s not necessary to include and use this package. Any other compatible routing library would also work with React.
The major components of React Router
are given below:
-
BrowserRouter
: It is a router implementation that will make use of the HTML5 history API (pushState, popstate, and event replaceState) for keeping your UI to be in sync with the URL. It is the parent component useful in storing all other components. -
Routes
: It is a newer component that has been introduced in the React v6 and an upgrade of the component. -
Route
: It is considered to be a conditionally shown component and some UI will be rendered by this whenever there is a match between its path and the current URL. -
Link
: It is useful in creating links to various routes and implementing navigation all over the application. It works similarly to the anchor tag in HTML.
What are the different phases of the component lifecycle
?
There are four different phases in the lifecycle of React component. They are:
-
Initialization
: During this phase, React component will prepare by setting up the default props and initial state for the upcoming tough journey. -
Mounting
: Mounting refers to putting the elements into the browser DOM. Since React uses VirtualDOM, the entire browser DOM which has been currently rendered would not be refreshed. This phase includes the lifecycle methodscomponentWillMount()
andcomponentDidMount()
. - Updating: In this phase, a component will be updated when there is a change in the state or props of a component. This phase will have lifecycle methods like
componentWillUpdate()
,shouldComponentUpdate()
,render()
, andcomponentDidUpdate()
. -
Unmounting
: In this last phase of the component lifecycle, the component will be removed from the DOM or will be unmounted from the browser DOM. This phase will have the lifecycle method namedcomponentWillUnmount
.
What are Higher Order Components
?
Higher-Order Component(HOC)
is a function that takes in a component and returns a new component.
In React, a higher-order component
is a function that takes a component as an argument and returns a new component that wraps the original component.
Benefits of Using Higher-Order Components
in React:
-
Reusability
: HOCs allow you to reuse component logic across multiple components, which can save time and reduce code duplication. -
Flexibility
: HOCs can take additional arguments, which allows you to customize the behavior of the HOC. This makes them a flexible way to add functionality to your components. -
Separation of concerns
: HOCs can help separate concerns in your code by encapsulating certain functionality in a separate component. This can make the code easier to read and maintain. -
Composition
: HOCs can be composed together to create more complex functionality. This allows you to build up functionality from smaller, reusable pieces. -
Higher-order components
can be used to implement cross-cutting concerns in your application such as authentication, error handling, logging, performance tracking, and many other features.
What is children
prop?
Children
is a prop that allows you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children
prop.
What are portals
in React?
Portal
is a recommended way to render children
into a DOM node that exists outside the DOM hierarchy of the parent component.
A portal
only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it. For example, the child can access the context provided by the parent tree, and events bubble up from children to parents according to the React tree.
Portals
let your components render some of their children
into a different place in the DOM. This lets a part of your component “escape” from whatever containers it may be in. For example, a component can display a modal
dialog or a tooltip
that appears above and outside of the rest of the page.
What is Redux
?
Redux
is a predictable state container for JavaScript apps based on the Flux design pattern. Redux
can be used together with React, or with any other view library. It is tiny (about 2kB) and has no dependencies.
Redux
is a predictable state container in Javascript app. What does that mean? Well, Redux
helps in state management by storing all the states which needs to be changed through out the app in one place, which we usually call it as Store
.
What is useLayoutEffect
hook?
useLayoutEffect
is a version of useEffect
that fires before the browser repaints the screen.
useLayoutEffect(setup, dependencies?)
Most components don’t need to know their position and size on the screen to decide what to render. They only return some JSX. Then the browser calculates their layout (position
and size
) and repaints the screen.
Sometimes, that’s not enough. Imagine a tooltip
that appears next to some element on hover. If there’s enough space, the tooltip
should appear above the element, but if it doesn’t fit, it should appear below. In order to render the tooltip
at the right final position, you need to know its height
(i.e. whether it fits at the top).
To do this, you need to render in two passes:
- Render the
tooltip
anywhere (even with a wrong position). - Measure its
height
and decide where to place thetooltip
. - Render the
tooltip
again in the correct place.
All of this needs to happen before the browser repaints the screen. You don’t want the user to see the tooltip
moving. Call useLayoutEffect
to perform the layout measurements before the browser repaints the screen:
function Tooltip() { const ref = useRef(null); const [tooltipHeight, setTooltipHeight] = useState(0); // You don't know real height yet useLayoutEffect(() => { const { height } = ref.current.getBoundingClientRect(); setTooltipHeight(height); // Re-render now that you know the real height }, []); // ...use tooltipHeight in the rendering logic below... }
Here’s how this works step by step:
- Tooltip renders with the initial
tooltipHeight = 0
(so the tooltip may be wrongly positioned). - React places it in the DOM and runs the code in
useLayoutEffect
. - Your
useLayoutEffect
measures theheight
of thetooltip
content and triggers an immediate re-render. -
Tooltip
renders again with the realtooltipHeight
(so the tooltip is correctly positioned). - React updates it in the DOM, and the browser finally displays the
tooltip
.
Notice that even though the Tooltip
component has to render in two passes (first, with tooltipHeight
initialized to 0
and then with the real measured height
), you only see the final result. This is why you need useLayoutEffect
instead of useEffect
for this example.
What is useInsertionEffect
hook?
useInsertionEffect
allows inserting elements into the DOM before any layout Effects fire.
useInsertionEffect(setup, dependencies?)
Call useInsertionEffect
to insert styles before any Effects fire that may need to read layout.
Traditionally, you would style React components using plain CSS
.
Some teams prefer to author styles directly in JavaScript code instead of writing CSS files. This usually requires using a CSS-in-JS library or a tool. There are three common approaches to CSS-in-JS:
- Static extraction to CSS files with a compiler
- Inline styles, e.g.
<div style={{ opacity: 1 }}>
- Runtime injection of
<style>
tags
If you use CSS-in-JS, we recommend a combination of the first two approaches (CSS files for static styles, inline styles for dynamic styles). We don’t recommend runtime <style>
tag injection for two reasons:
- Runtime injection forces the browser to recalculate the styles a lot more often.
- Runtime injection can be very slow if it happens at the wrong time in the React lifecycle.
The first problem is not solvable, but useInsertionEffect
helps you solve the second problem.
Call useInsertionEffect
to insert the styles before any layout Effects fire:
// Inside your CSS-in-JS library let isInserted = new Set(); function useCSS(rule) { useInsertionEffect(() => { // As explained earlier, we don't recommend runtime injection of <style> tags. // But if you have to do it, then it's important to do in useInsertionEffect. if (!isInserted.has(rule)) { isInserted.add(rule); document.head.appendChild(getStyleForRule(rule)); } }); return rule; } function Button() { const className = useCSS('...'); return <div className={className} />; }
Similarly to useEffect
, useInsertionEffect
does not run on the server. If you need to collect which CSS rules have been used on the server, you can do it during rendering:
let collectedRulesSet = new Set(); function useCSS(rule) { if (typeof window === 'undefined') { collectedRulesSet.add(rule); } useInsertionEffect(() => { // ... }); return rule; }
What is useDebugValue
hook?
useDebugValue
is a React Hook that lets you add a label to a custom Hook in React DevTools.
useDebugValue(value, format?)
Call useDebugValue
at the top level of your custom Hook to display a readable debug value:
import { useDebugValue } from 'react'; function useOnlineStatus() { // ... useDebugValue(isOnline ? 'Online' : 'Offline'); // ... }
This gives components calling useOnlineStatus
a label like OnlineStatus
: “Online” when you inspect them.
Without the useDebugValue
call, only the underlying data (in this example, true
) would be displayed.
What is useId
hook?
useId
is a React Hook for generating unique IDs that can be passed to accessibility attributes.
const id = useId()
import { useId } from 'react'; function PasswordField() { const passwordHintId = useId(); // ...
You can then pass the generated ID to different attributes:
<> <input type="password" aria-describedby={passwordHintId} /> <p id={passwordHintId}> </>
Hardcoding IDs like this is not a good practice in React. A component may be rendered more than once on the page—but IDs have to be unique! Instead of hardcoding an ID, generate a unique ID with useId
.
What is useSyncExternalStore
hook?
useSyncExternalStore
is a React Hook that lets you subscribe to an external store.
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)
Call useSyncExternalStore
at the top level of your component to read a value from an external data store.
import { useSyncExternalStore } from 'react'; import { todosStore } from './todoStore.js'; function TodosApp() { const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot); // ... }
It returns the snapshot of the data in the store. You need to pass two functions as arguments:
- The subscribe function should subscribe to the store and return a function that unsubscribes.
- The
getSnapshot
function should read a snapshot of the data from the store.
Most of your React components will only read data from their props
, state
, and context
. However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes:
- Third-party state management libraries that hold state outside of React.
- Browser APIs that expose a mutable value and events to subscribe to its changes.
Usually you won’t write useSyncExternalStore
directly in your components. Instead, you’ll typically call it from your own custom Hook. This lets you use the same external store from different components.
If your React app uses server rendering, your React components will also run outside the browser environment to generate the initial HTML. This creates a few challenges when connecting to an external store:
- If you’re connecting to a browser-only API, it won’t work because it does not exist on the server.
- If you’re connecting to a third-party data store, you’ll need its data to match between the server and client.
To solve these issues, pass a getServerSnapshot
function as the third argument to useSyncExternalStore
:
import { useSyncExternalStore } from 'react'; export function useOnlineStatus() { const isOnline = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); return isOnline; } function getSnapshot() { return navigator.onLine; } function getServerSnapshot() { return true; // Always show "Online" for server-generated HTML } function subscribe(callback) { // ... }
The getServerSnapshot function is similar to getSnapshot, but it runs only in two situations:
- It runs on the server when generating the HTML.
- It runs on the client during hydration, i.e. when React takes the server HTML and makes it interactive.
What is useTransition
hook?
useTransition
is a React Hook that lets you render a part of the UI in the background.
const [isPending, startTransition] = useTransition()
import {useState, useTransition} from 'react'; function CheckoutForm() { const [isPending, startTransition] = useTransition(); // ... }
useTransition
returns an array with exactly two items:
- The
isPending
flag that tells you whether there is a pending Transition. - The
startTransition
function that lets you mark updates as a Transition.
The function passed to startTransition is called the “Action”. You can update state and (optionally) perform side effects within an Action, and the work will be done in the background without blocking user interactions on the page. A Transition can include multiple Actions, and while a Transition is in progress, your UI stays responsive. For example, if the user clicks a tab but then changes their mind and clicks another tab, the second click will be immediately handled without waiting for the first update to finish.
What is useDeferredValue
hook?
useDeferredValue
is a React Hook that lets you defer updating a part of the UI.
const deferredValue = useDeferredValue(value)
import { useState, useDeferredValue } from 'react'; function SearchPage() { const [query, setQuery] = useState(''); const deferredQuery = useDeferredValue(query); // ... }
During the initial render, the deferred value will be the same as the value you provided.
During updates, the deferred value will “lag behind” the latest value. In particular, React will first re-render without updating the deferred value, and then try to re-render with the newly received value in the background.
What is useImperativeHandle
hook?
useImperativeHandle
is a React Hook that lets you customize the handle exposed as a ref
.
useImperativeHandle(ref, createHandle, dependencies?)
To expose a DOM node to the parent element, pass in the ref
prop to the node.
function MyInput({ ref }) { return <input ref={ref} />; };
With the code above, a ref to MyInput
will receive the <input>
DOM node. However, you can expose a custom value instead. To customize the exposed handle, call useImperativeHandle
at the top level of your component:
import { useImperativeHandle } from 'react'; function MyInput({ ref }) { useImperativeHandle(ref, () => { return { // ... your methods ... }; }, []); return <input />; };
Note that in the code above, the ref is no longer passed to the <input></input>.
For example, suppose you don’t want to expose the entire <input>
DOM node, but you want to expose two of its methods: focus
and scrollIntoView
. To do this, keep the real browser DOM in a separate ref
. Then use useImperativeHandle
to expose a handle with only the methods that you want the parent component to call:
import { useRef, useImperativeHandle } from 'react'; function MyInput({ ref }) { const inputRef = useRef(null); useImperativeHandle(ref, () => { return { focus() { inputRef.current.focus(); }, scrollIntoView() { inputRef.current.scrollIntoView(); }, }; }, []); return <input ref={inputRef} />; };
Now, if the parent component gets a ref
to MyInput
, it will be able to call the focus
and scrollIntoView
methods on it. However, it will not have full access to the underlying <input>
DOM node.
What is component-driven development (CDD)
?
In component-based development, we are building UIs by creating small pieces of interface that are well specified and documented. Those small bits of UI are what we are going to call components. They can be used together to create more and more complex layout and functionality, and finally, to create new screens by composition.
A component can be defined as a self-contained unit of interface that handles the visuals (styles), the interaction (behavior) and the purpose (functionality) for a particular use case in an app.
Components have the following properties:
- They are reusable. They are self-contained and provide functionality that can be needed in multiple places of our UI. We need to create them with re-utilization in mind and enforce it over creating new components.
- They are consistent. No matter where we use them, components need to look the same, behave in the same way and offer the same functionality defined in their specification.
- They are configurable. Components might accept some parameters that customize the way they work. This way they are flexible enough to adapt them to slightly different situations without the need for coding again.
In a component-driven
approach, we put the focus on how to create every part of a screen so they can work independently, but in a coordinated way in order to make the screen work as required. Even if our goal is to deliver the screen, we are thinking ahead: the components are made to be reused in the future.