Professional Documents
Culture Documents
React Combined
React Combined
Answer:
● Component-based architecture
● Virtual DOM for efficient updates
● Reusable components
● Strong community support
● Integration capability with various backends
● Concurrent mode for smoother UI interactions
Answer:
Answer: React Components are reusable pieces of the UI that can manage
their own state, structure, and rendering. They can be class-based or
functional and are the building blocks of a React application.
Answer: The public folder contains assets that are publicly available,
like the index.html file, images, or other static files that aren't
processed by Webpack.
Answer: The src folder contains the main source code for your React
application, including components, styles, and logic.
Answer: index.html is the main HTML file that gets loaded in the
browser. It contains the root div (<div id="root"></div>) where the
React application gets mounted.
Answer: The function inside App.js defines the App component, and the
return statement describes what the UI looks like for that component
using JSX.
Answer: export default allows the App component to be imported and used
in other files/modules.
Q19. What is the role of index.js file, ReactDOM, and render method in React?
Q20. How does a React App load and display the components in the browser?
Answer: React uses ReactDOM's render method to mount the root component
(often App) to the root div in index.html. From there, components are
nested, and React efficiently updates and renders only the necessary
components when data changes.
Answer:
Answer: While JSX is closely associated with React, it's not exclusive
to it. JSX is just a syntax, so it can be used with other libraries or
frameworks if they provide a mechanism to transform it, though this is
less common.
Q27. How do you iterate over a list in JSX? What is the use of the map
method?
Answer: You can use the map method to iterate over a list in JSX. It
allows you to transform each item in an array and typically results in
an array of JSX elements.
Answer: Props (short for "properties") are a way to pass data from
parent to child components. They are read-only and help components to
be reusable.
1. Ternary Operator:
2. Short-Circuit Evaluation:
3. If/Else Statements: This is not directly inside JSX, but you can
use if/else logic before the return statement to decide which
component to render.
4. Switch/Case: Similar to if/else, but can be useful when you have
multiple conditions to check.
5. IIFE (Immediately Invoked Function Expression):
{(() => {
})()}
Answer: React hooks are functions introduced in React 16.8 that allow
you to use state and other React features without writing a class
component. Examples include useState, useEffect, and useContext.
Answer: useState is a hook that lets you add React state to functional
components. It returns an array where the first element is the current
state, and the second element is a function to update that state.
Answer: The Context API in React provides a way to pass data through
the component tree without having to pass props manually at every
level. It's useful for sharing data that can be considered "global",
such as themes, user authentication, etc.
Answer: React forms are typically controlled. This means the form data
is handled by the React component's state and not by the DOM directly.
Input changes are captured by event handlers which then update the
component state.
Answer: React Portals provide a way to render children into a DOM node
outside of the parent DOM hierarchy, useful for modals, popups, or any
UI overlay that should be above other content.
Answer: With React 16 and above, you can handle errors using Error
Boundaries. An error boundary is a React component that catches
JavaScript errors anywhere in its child component tree and renders a
fallback UI.
Answer: Keys are special string attributes you should include when
creating lists of elements in React. They help React identify which
items have changed, are added, or are removed, which in turn helps in
efficiently re-rendering lists.
Q47. What is prop drilling and how can you avoid it?
Answer: Prop drilling refers to the process of passing data from one
part of the React component tree to another by going through other
Q50. What are React lifecycle methods and how are they used?
V1.02
HEEELLLOOOOO!
I’m Andrei Neagoie, Founder and Lead Instructor of the Zero To Mastery Academy.
After working as a Senior Software Developer over the years, I now dedicate 100% of my time to
teaching others in-demand skills, help them break into the tech industry, and advance their
careers.
In only a few years, over 1,000,000 students around the world have taken Zero To Mastery courses
and many of them are now working at top tier companies like Apple, Google, Amazon, Tesla, IBM,
Facebook, and Shopify, just to name a few.
This cheat sheet, created by our React instructor (Yihua Zhang) provides you with the key React
information and concepts that you need to know.
If you want to not only learn React but also get the exact steps to build your own projects and get
hired as a Frontend or Fullstack Developer, then check out our Career Paths.
Happy Coding!
Andrei
React Elements
React Element Tags
React Element Attributes
React Components
Functional Components
Component Props
The Children Prop
Conditional Rendering
Lists in Components
Memo
Context
Hooks
useState
useEffect
useLayoutEffect
useRef
useCallback
useMemo
React Cheatsheet 1
useContext
Class Component
Constructor
State
Lifecycle Methods
componentDidMount
componentWillUnmount
componentDidUpdate
Error Boundaries
getDerivedStateFromError
componentDidCatch
Useful Links
React Cheatsheet 2
JSX
Almost all React code is written in JSX. JSX is a syntax extension of Javascript that
allows us to write HTML-like syntax in Javascript.
React Elements
React Element Tags
React elements look just like HTML, in fact they render the same equivalent HTML
elements.
<h1>My Header</h1>
<button>My Button</button>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>
Single tag elements like the img element and the br element must be closed like so
<div className="my-container">
<img className="my-container-image" src="my-image.jpeg"/>
</div>
React Cheatsheet 3
React Elements Embedded Javascript
The power of JSX is that it’s javascript and HTML. This means you can write javascript to
render different attributes directly in your javascript using curly braces {} .
<div className={divClass}></div>
In HTML
In JSX
React Fragments
React has a special element called a fragment. It’s a special element that doesn’t actually
render into the DOM, but can act as a parent to a group of elements.
<Fragment>
<h1> My H1 </h1>
<p> My Paragraph </p>
</Fragment>
If you don’t want to import Fragment from the React library, you can also use <> .
<>
<h1> My H1 </h1>
<p> My Paragraph </p>
</>
React Cheatsheet 4
Fragments are useful in components since components require us to return one parent
level element, and if we don’t want to needlessly add HTML elements to our website, we
can just use fragments.
React Components
Components are the building blocks of your web application. We use them to organize
groups of React elements together so they’re reusable. There are two kinds of
components, class components and functional components but functional components
are the de facto standard today. They both follow the same two rules:
2. They must return JSX, more specifically one parent level JSX element (more on this
later).
Functional Components
Functional components are just javascript functions that return JSX.
Here's how you create a functional component using function declaration:
function MyComponent() {
return <h1>My Component</h1>
}
React Cheatsheet 5
<div>
<MyComponent />
<p> Sample Text </p>
</div>
)
}
Component Props
We can pass data to our components through custom attributes on the component
element. We can choose any name for the attribute as long they don’t overlap with the
existing general element attributes (i.e. className , styles , onClick etc.). These properties
are then grouped into an object where the attribute name is the key, and the value is the
value. Here we are passing a prop title from the App component to our component
MyComponent .
Remember, you can embed any of the values in your props object in JSX since it’s just
javascript, just remember to use curly braces ( {} ).
Since the props are just an object, it’s common to destructure the values for cleaner,
simpler code.
React Cheatsheet 6
Any JavaScript value can be passed as a prop such as arrays, objects, other elements
and components!
We can render it anywhere in our component’s JSX! Just remember that it’s a javascript
variable so make sure it’s wrapped in curly braces {} .
React Cheatsheet 7
Conditional Rendering
Since our components are written in JSX which is just javascript, we can conditionally
render different things with javascript. A basic example is to use an if statement in our
functional component.
React Cheatsheet 8
<Greeting message="not rendered!" display={false}/> // nothing rendered
</div>
)
}
Lists in Components
If we want to duplicate elements/components, we can do so by looping through an array
with the .map() method as long as we return JSX from the callback.
Remember, this is javascript so wrap your map call in {} . We must remember to add the
attribute key to the top level JSX element we return from map ; the value must also be a
unique value for each iteration.
IMPORTANT REMINDER
Remember, when mapping over an array into JSX, you must include a key attribute with
a unique value. It’s tempting to use the index from map but this may cause issues down
the road.
React Cheatsheet 9
The reason is because React uses the key to determine which components to re-render,
with the keys themselves being unique identifiers hence why the values need to be
unique. Indexes are just numbers and in lists where there are multiple maps, if you always
use the index as the key React may get confused.
return (
<ul>
{vegetables.map((veg, idx) => <li key={idx}> {veg} </li>)}
{meats.map((meat, idx) => <li key={idx}> {meat} </li>)}
</ul>
)
}
As you can see in the above example, the map of vegetables has indexes 0, 1 and 2
since there are 3 items. The map for meats will be have index 0 and 1 since there are 2
items. This is a problem since React can’t differentiate the vegetable item with key 0 and
the meat item with key 0, or the vegetable item with key 1 and the meat item with key 1.
This is why we need to use unique keys !
Below we can fix this using the name attribute, which we know are unique.
return (
<ul>
{vegetables.map((veg) => {<li key={veg}> {veg} </li>})}
{meats.map((meat) => {<li key={meat}> {meat} </li>})}
</ul>
)
}
Memo
Use react.memo allows a component to skip re-rendering if it’s props haven’t
changed when it’s parent re-renders.
React Cheatsheet 10
When a component re-renders, all its child components will also re-render. Wrapping a
component in react.memo will prevent that component re-rendering caused by upstream
re-renders if the props have not changed.
The second argument is a custom comparison function that for the majority of
circumstances are not needed. When not passed a second argument, react defaults to
shallow comparison of the old props and new props with Object.is . If you need custom
comparison, the function should return true if the props are equal and therefore not re-
render. Or it should return false if the props are not equal and should re-render.
Context
If we had some data values we wanted to share across multiple sibling or nested child
components, we would have to lift that data up to a commonly shared parent and
needlessly drill it down through multiple components and their props. Take the following
example
React Cheatsheet 11
const ChildA = ({ text }) => { // I don't need text
return (
<div>
<h1> Child A </h1>
<GrandChildA text={text} />
</div>
)
}
return (
<div>
<h1> App </h1>
<ParentA text={text} />
<ParentB text={text} />
</div>
)
}
Here, we have to pass the text value from the App component all the way through Parent
A and ChildA just so GrandChildA can receive it, even though ParentA and ChildA don’t
need the text other than to pass it down. The same is true for ParentB in order to get the
text value to ChildB . This is called prop drilling.
React Cheatsheet 12
We can’t move the text value down the tree since both GrandChildA and ChildB need it,
and App is the lowest common parent between them. This makes our code extremely
brittle since moving and the components serving to pass the text prop needlessly
complex.
We can solve this with React Context which allows us to lift the data into a special
component called Context that allows any of it’s children no matter where they are to
access it’s values without the need for prop drilling.
We need the createContext function from React and pass it the initial value we want to
share. It returns us back an object that contains two components:
1. the Provider component which we wrap around the portion of the component tree we
want to access the value.
2. The Consumer component which has access to the values from the created context
which we place in any component that needs the value.
React Cheatsheet 13
}
Hooks
Hooks were introduced in React version 16.8 as a way to extend additional functionality
into functional components. Previously this functionality was only available to class
components, but through hooks we can super charge our functional components!
To better understand hooks, we need to understand the React component lifecycle. There
are three main phases of any React component:
1. The mounting phase when a component is created and inserted into the DOM. This is
the initial render and only happens once in a components lifecycle.
2. The updating phase is when a component re-renders due to updates. This happens
either due to prop changes or state changes (more below).
React Cheatsheet 14
3. The final phase is the un-mounting phase, when a component is removed from the
DOM.
useState
useStatehook allows us to store values scoped to a component. Any changes to
those values will cause the component and any of it’s child components to re-
render.
As mentioned above, components re-render in the updating phase (2) due to prop
changes and state changes. State is data stored inside of a component that can be
updated/changed. When this state data changes, this will trigger a re-render of the
component. While we can store and change data in a variable, those changes will not
trigger a re-render. With the useState hook, it does allow us to trigger re-renders on
changes to that data.
useState is a function that we can pass an optional argument representing the initial value
we want to store. The useState hook returns back an array containing two values, the first
is the current state value, the second is a setter function to update this state value.
The setValue function we de-structured is called the setter function. When we call this
setter function, we pass it the new value we want to set the state to.
return (
<div>
{count}
<button onClick={increment}> increment </button>
React Cheatsheet 15
<button onClick={decrement}> decrement </button>
</div>
)
}
Whenever setCount is called, the Counter component will re-render, which is the
behaviour we want since count is has updated and we want our DOM to display the new
value.
It’s important to note that the setter function from useState is asynchronous. This means
that if you try to log the state immediately after setting it, you might not see the updated
state.
useEffect
is a hook that allows us to create side effects in our functional
useEffect
components.
useEffect takes two arguments:
1. The first argument is a callback function called the effect function that contains the
side effect code we want to run.
2. The second argument is an array called the dependency array which contains values
from outside the scope of the effect function. Whenever one of these values changes,
useEffect will run the effect function.
A common use case for useEffect is to fetch some data and store it in a state variable.
React Cheatsheet 16
import { useState, useEffect } from 'react'
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => setUserList(users))
}, []);
return (
<div>
{ userList.map(user => <h2 key={user.id}> {user.name} </h2>) }
</div>
)
}
Passing an empty dependency array will only call our effect function once during the
mounting phase since there are no dependencies to react to.
The effect function will run every time a value in the dependency array changes. Values
the effect function relies on but comes from outside of it’s scope are added to the
dependency array. These include props:
useEffect(() => {
fetch(sourceURL)
.then(response => response.json())
.then(users => setUserList(users))
}, [sourceURL]);
return (
<div>
{ userList.map(user => <h2 key={user.id}> {user.name} </h2>) }
</div>
)
}
React Cheatsheet 17
import { useState, useEffect } from 'react';
useEffect(() => {
userAPI.getByUsername(userName)
.then(user => setUser(user))
}, [userName]);
return (
<div>
<h2> Search by username </h2>
<input type='text' onChange={handleTextChange} />
<User user={user} />
</div>
)
}
useEffect(() => {
ChatAPI.subscribeToUser(userID);
It’s important to note, the effect function runs after React renders/re-renders the
component to ensure our effect callback does not block browser painting.
useLayoutEffect
The useLayoutEffect hook is almost identical to the useEffect hook except it runs the
effect callback immediately after DOM changes.
React Cheatsheet 18
The one key difference between the useLayoutEffect hook and useEffect hook:
useLayoutEffect runs the effect callback synchronously immediately after React has
performed all DOM mutations, but before the browser has a chance to paint. This is useful
if you need to make DOM mutations and don't want the screen to flicker between renders.
useRef
useRef is a hook that stores a value in a component like useState except changes to
that value won’t cause the component to re-render.
It accepts one argument as the initial value and returns a reference object.
{
current: initialValue
}
We can access and mutate the current value of the ref through the ref.current property.
This value will persist across re-renders.
React Cheatsheet 19
function handleClick() {
ref.current = ref.current + 1;
}
return (
<>
<h1>count: {ref.current} </h1>
<button onClick={handleClick}>
Click me!
</button>
</>
);
}
Every time we click the button and trigger handleClick , we are incrementing the
ref.current value. However, because this mutation does not trigger the component to re-
render, so the count does not update in the DOM even though the stored value is
updating.
It is common to store DOM node references in a ref.
function InputFocus() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<input
ref={inputRef}
type="text"
/>
);
}
When the InputFocus component mounts, we will call on the DOM node for the input and
automatically focus it.
useCallback
The useCallback hook is a performance improvement hook that prevents functions
from being needlessly recreated between re-renders.
React Cheatsheet 20
Whenever a component renders or re-renders, any functions that are created are
recreated. In the component below, we create a hideUser function that we use in the
button.
2. A dependency array containing values that tells useCallback when to recreate the
function when any of them change.
Looking at an example
return (
<div>
{userList.map(user => (
<div key={user.id}>
<h2> {user.name} </h2>
<button onClick={() => hideUser(user.id)}> hide user </button>
</div>
))}
</div>
)
}
React Cheatsheet 21
{id: 4, name: 'Pierre'}
];
return (
<div>
{userList.map(user => (
<div key={user.id}>
<h2> {user.name} </h2>
<button onClick={() => hideUser(user.id)}> hide user </button>
</div>
))}
</div>
)
}
];
React Cheatsheet 22
Now the hideUser function will only recreate if the users prop changes.
useMemo
The useMemo is a performance improvement hook that memoizes the return value of
a function.
Memoization is the caching of computed results from a expensive function call and
returning the cached result when the function is called with the same inputs.
2. A dependency array containing values that the function uses. When any of these
values change it tells useMemo to rerun the function (with the new values) and
memoize the new return value.
React Cheatsheet 23
const factorialNumber = factorialOf(number); // Computationally expensive
return (
<div>
<input type='text' onChange={(event) => setNumber(event.target.value)} />
<h2>{ factorialNumber }</h2>
<button onClick={clickHandler}> re-render </button>
</div>
)
}
recalculate factorialNumber needlessly whenever the component re-renders (it’s parent re-
renders or state changes unrelated to number i.e. setBool is called). We can fix this with
useMemo
return (
<div>
<input type='text' onChange={(event) => setNumber(event.target.value)} />
<h2>{ factorialNumber }</h2>
<button onClick={clickHandler}> re-render </button>
</div>
)
}
React Cheatsheet 24
Here, factorialNumber will compute the value from factorialOf once per input of number
and cache it. Any future calls of factorialOf with the same number will return the cached
value saving us expensive and needless re-computations.
useContext
useContext allows us to access Context without need to use it’s Consumer component.
Without useContext
To use the useContext hook, we pass it the context value we want to access.
React Cheatsheet 25
const ChildA = () => {
const text = useContext(TextContext);
return (
<div>
<p> {text} </p>
</div>
)
}
Class Component
Class components are the other type of component we can write. The common practice is
to use functional components but there are some existing use cases that still call for class
components. The JSX for the component is returned from the render method.
React Cheatsheet 26
constructor
The constructor method runs before the class component mounts.
Typically used to declare the initial state and bind custom class methods to the class
instance.
increment() {
// increment code
}
...
}
However, modern javascript syntax does not require a constructor . We can just use public
class fields.
increment() {
// increment code
}
...
}
You access all methods, props and state of the class instance with the this keyword.
State
After initializing state in the component, the class instance has a setState method that
you must use if you wish to update the state. Do not mutate the state object!
setState(nextState, callback?)
You can pass setState two arguments, with the second being optional.
React Cheatsheet 27
1. The next state, either an object or a function.
a) With an object, just with the new fields you want updated. React will perform a shallow
merge of the new state object against the previous state object.
render() {
return (
<>
<input value={this.state.name} onChange={this.handleNameChange} />
<input value={this.state.address} onChange={this.handleAddressChange} />
<p>Hello, {this.state.name}. You live at {this.state.address} </p>
</>
);
}
}
b) With a pure function that receives the prevState and props. It should return the state
object to be shallowly merged with the previous state object.
increment = () => {
this.setState((prevState) => ({count: prevState.count + 1}))
}
React Cheatsheet 28
decrement = () => {
this.setState((prevState) => ({count: prevState.count - 1}))
}
render() {
return (
<>
<p> { this.state.count } </p>
<button onClick={this.increment}> Increment </button>
<button onClick={this.decrement}> Decrement </button>
</>
);
}
}
render() {
return (
<>
<input value={this.state.name} onChange={this.handleNameChange} />
<p>Hello, {this.state.name} </p>
</>
);
}
}
Lifecycle Methods
Class components also have methods that hook into React’s rendering and re-rendering
cycles called lifecycle methods. Many methods are now deprecated or considered
UNSAFE as the React team is pushing forward with functional components + hooks. This
cheatsheet will only reference the commonly used ones.
React Cheatsheet 29
The full list can be found here
componentDidMount
The componentDidMount method calls after react mounts the component to the DOM.
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({users: users}
}
render() {
return (
<div>
<h1> My Class Component </h1>
</div>
)
}
}
React Cheatsheet 30
componentWillUnmount
The componentWillUnmount method is called immediately before the component
unmounts. It is commonly used for cleanup.
componentWillUnmount() {
ChatAPI.unsubscribeFromUser(userID);
}
render() {...}
}
componentDidUpdate
The componentDidUpdate method is called immediately after the component has re-
rendered from state or prop changes (ignoring the initial render).
A method that receives previous props and previous state which can be compared with
new state and props . This is often used to make network requests if needed. Take the
following example
componentDidMount() {
// open new subscription
chatAPI.subscribe(this.serverUrl, this.props.roomID);
}
React Cheatsheet 31
componentDidUpdate(prevProps, prevState) {
// Check if we've changed rooms or server
if (
this.props.roomID !== prevProps.roomID ||
this.state.serverUrl !== prevState.serverURL
) {
// unsubscribe from previous room and server
chatAPI.unsubscribe(prevState.serverURL, prevProps.roomID);
// subscribe to new room and server
chatAPI.subscribe(this.serverUrl, this.props.roomID);
}
}
componentWillUnmount() {
// close all subscriptions
chatAPI.unsubscribeAll();
}
// ...
}
Error Boundaries
getDerivedStateFromError
Error boundaries are components that catch errors that occur anywhere in their
child component tree. It allows us to display some fallback UI instead of the
component that crashed.
It is a class component we create that has a static getDerivedStateFromError method which
can update state in response to an error.
We wrap this error boundary component around the portion of our component tree we
want our fallback UI for. To set this up, we create state that tracks whether or not there is
an error. From the static getDerivedStateFromError method, we return the new state object
with the updated error state.
static getDerivedStateFromError(error) {
return { hasError: true };
}
React Cheatsheet 32
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>; // Fallback UI
}
return this.props.children;
}
}
componentDidCatch
The componentDidCatch lifecycle method runs when a child component in its
component tree throws an error during rendering.
The method receives two parameters, the error that was thrown as well as info about
the rendering issue. It is commonly used in a Error Boundary component to log the error
to some error reporting service.
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
errorService.log(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>; // Fallback UI
}
React Cheatsheet 33
return this.props.children;
}
}
Useful Links
1. React Documentation
React Cheatsheet 34
React Interview Questions
© Copyright by Interviewbit
Contents
Introduction to React
...
const [count, setCounter] = useState(0);
const [otherStuffs, setOtherStuffs] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setOtherStuffs(...);
...
};
We can make use of setCounter() method for updating the state of count anywhere.
In this example, we are using setCounter() inside the setCount function where various
other things can also be done. The idea with the usage of hooks is that we will be able
to keep our code more functional and avoid class-based components if they are not
required.
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.
***Note- Keys used within arrays should be unique among siblings. They need
not be globally unique.
6. 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( ).
As stated in the official docs of React, JSX provides syntactic sugar for
React.createElement( ) function.
Note- We can create react applications without using JSX as well.
Let’s understand how JSX works:
Without using JSX, we would have to create an element by the following process:
const container = (
<div>
<p>This is a text</p>
</div>
);
ReactDOM.render(container,rootElement);
As one can see in the code above, we are directly using HTML inside JavaScript.
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.
On the following basis let’s compare functional and class components:
Declaration
Functional components are nothing but JavaScript functions and therefore can be
declared using an arrow function or the function keyword:
function card(props){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
const card = (props) =>{
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
Class components, on the other hand, are declared using the ES6 class:
Handling props
Let’s render the following component with props and analyse how functional and
class components handle props:
function StudentInfo(props){
return(
<div className="main">
<h2>{props.name}</h2>
<h4>{props.rollNumber}</h4>
</div>
)
}
As we can see in the code above, this keyword is used in the case of class
components.
Handling state
Functional components use React hooks to handle state. It uses the useState hook to
set the state of a variable inside the component:
function ClassRoom(props){
let [studentsCount,setStudentsCount] = useState(0);
const addStudent = () => {
setStudentsCount(++studentsCount);
}
return(
<div>
<p>Number of students in class room: {studentsCount}</p>
<button onClick={addStudent}>Add Student</button>
</div>
)
}
Since useState hook returns an array of two items, the first item contains the current
state, and the second item is a function used to update the state.
In the code above, using array destructuring we have set the variable name to
studentsCount with a current value of “0” and setStudentsCount is the function that
is used to update the state.
For reading the state, we can see from the code above, the variable name can be
directly used to read the current state of the variable.
We cannot use React Hooks inside class components, therefore state handling is
done very differently in a class component:
Let’s take the same above example and convert it into a class component:
this.addStudent = this.addStudent.bind(this);
}
addStudent(){
this.setState((prevState)=>{
return {studentsCount: prevState.studentsCount++}
});
}
render(){
return(
<div>
<p>Number of students in class room: {this.state.studentsCount}</p>
<button onClick={this.addStudent}>Add Student</button>
</div>
)
}
}
In the code above, we see we are using this.state to add the variable studentsCount
and setting the value to “0”.
For reading the state, we are using this.state.studentsCount.
For updating the state, we need to first bind the addStudent function to this. Only
then, we will be able to use the setState function which is used to update the state.
8. 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.
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.
**Note- One may think updating every virtual DOM object might be inefficient,
but that’s not the case. Updating the virtual DOM is much faster than updating
the real DOM since we are just updating the blueprint of the real DOM.
React uses two virtual DOMs to render the user interface. One of them is used to store
the current state of the objects and the other to store the previous state of the
objects. Whenever the virtual DOM gets updated, react compares the two virtual
DOMs and gets to know about which virtual DOM objects were updated. A er
knowing which objects were updated, react renders only those objects inside the real
DOM instead of rendering the complete real DOM. This way, with the use of virtual
DOM, react solves the problem of inefficient updating.
One-time
value
retrieval ✔ ✔ ✔
(e.g. on
submit)
Validating on
✔ ✔ ✔
submit
Field-level
❌ ✔ ✔
Validation
Conditionally
disabling
❌ ✔ ✔
submit
button
Enforcing
❌ ✔ ✔
input format
several
inputs for
❌ ✔ ✔
one piece of
data
dynamic
❌ ✔
inputs
function FormValidation(props) {
let [inputValue, setInputValue] = useState("");
let updateInput = e => {
setInputValue(e.target.value);
};
return (
<div>
<form>
<input type="text" value={inputValue} onChange={updateInput} />
</form>
</div>
);
}
As one can see in the code above, the value of the input element is determined by the
state of the inputValue variable. Any changes made to the input element is handled
by the updateInput function.
Uncontrolled component: In an uncontrolled component, the value of the input
element is handled by the DOM itself. Input elements inside uncontrolled
components work just like normal HTML input form elements.
The state of the input element is handled by the DOM. Whenever the value of the
input element is changed, event-based callbacks are not called. Basically, react does
not perform any action when there are changes made to the input element.
Whenever use enters data inside the input field, the updated data is shown directly.
To access the value of the input element, we can use ref.
function FormValidation(props) {
let inputValue = React.createRef();
let handleSubmit = e => {
alert(`Input value: ${inputValue.current.value}`);
e.preventDefault();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" ref={inputValue} />
<button type="submit">Submit</button>
</form>
</div>
);
}
As one can see in the code above, we are not using onChange function to govern the
changes made to the input element. Instead, we are using ref to access the value of
the input element.
Props State
React State
Every component in react has a built-in state object, which contains all the
property values that belong to that component.
In other words, the state object controls the behaviour of a component. Any
change in the property values of the state object leads to the re-rendering of the
component.
Note- State object is not available in functional components but, we can use
React Hooks to add state to a functional component.
How to declare a state object?
Example:
As one can see in the code above, we can use the state by calling
this.state.propertyName and we can change the state object property using
setState method.
React Props
Every React component accepts a single object argument called props (which stands
for “properties”). These props can be passed to a component using HTML attributes
and the component accepts these props as an argument.
<Car brand="Mercedes"/>
In Functional component:
function Car(props) {
let [brand, setBrand] = useState(props.brand);
}
Effects without Cleanup: This side effect will be used in useEffect which does
not restrict the browser from screen update. It also improves the responsiveness
of an application. A few common examples are network requests, Logging,
manual DOM mutations, etc.
Effects with Cleanup: Some of the Hook effects will require the cleanup a er
updating of DOM is done. For example, if you want to set up an external data
source subscription, it requires cleaning up the memory else there might be a
problem of memory leak. It is a known fact that React will carry out the cleanup
of memory when the unmounting of components happens. But the effects will
run for each render() method rather than for any specific method. Thus we can
say that, before execution of the effects succeeding time the React will also
cleanup effects from the preceding render.
Sometimes while developing React applications, there is a need to pass data from a
component that is higher in the hierarchy to a component that is deeply nested. To
pass data between such components, we pass props from a source component and
keep passing the prop to the next component in the hierarchy till we reach the
deeply nested component.
The disadvantage of using prop drilling is that the components that should
otherwise be not aware of the data have access to the data.
In the code above, when the counterValue equals 2, we throw an error inside the
render method.
When we are not using the error boundary, instead of seeing an error, we see a blank
page. Since any error inside the render method leads to unmounting of the
component. To display an error that occurs inside the render method, we use error
boundaries.
With error boundaries: As mentioned above, error boundary is a component using
one or both of the following methods: static getDerivedStateFromError and
componentDidCatch.
Let’s create an error boundary to handle errors in the render phase:
<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>
function Person(props) {
// We are declaring a state variable called name.
// setName is a function to update/change the value of name
let [name, setName] = useState('');
}
The state variable “name” can be directly used inside the HTML.
17. What are the rules that must be followed while using React
Hooks?
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 React Function Components.
Where the first argument callback represents the function having the logic of side-
effect and it will be immediately executed a er 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.
Example:
The above code will update the document title which is considered to be a side-effect
as it will not calculate the component output directly. That is why updating of
document title has been placed in a callback and provided to useEffect().
Consider you don’t want to execute document title update each time on rendering of
WelcomeGreetings component and you want it to be executed only when the name
prop changes then you need to supply name as a dependency to useEffect(callback,
[name]) .
function App() {
return (
<React.StrictMode>
<div classname="App">
<Header/>
<div>
Page Content
</div>
<Footer/>
</div>
</React.StrictMode>
);
}
The Parent component is the parent component and the Message is the child
component. Any change in the parent component will lead to re-rendering of
the child component as well. To prevent the re-rendering of child components,
we use the shouldComponentUpdate( ) method:
**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s
a static component.
As one can see in the code above, we have returned false from the
shouldComponentUpdate( ) method, which prevents the child component from re-
rendering.
Using JavaScript object: We can create a separate JavaScript object and set the
desired style properties. This object can be used as the value of the inline style
attribute.
headingStyles = {
color: "blue",
fontSize: "48px"
};
render() {
return (
<div>
<h3 style={this.headingStyles}>This is a heading</h3>
<p style={this.paragraphStyles}>This is a paragraph</p>
</div>
);
}
}
CSS Stylesheet: We can create a separate CSS file and write all the styles for the
component inside that file. This file needs to be imported inside the component
file.
import './RandomComponent.css';
CSS Modules: We can create a separate CSS module and import this module
inside our component. Create a file with “.module.css”‘ extension,
styles.module.css:
.paragraph{
color:"red";
border:1px solid black;
}
We can import this file inside the component and use it:
Using useMemo( ) -
It is a React hook that is used for caching CPU-Expensive functions.
Sometimes in a React app, a CPU-Expensive function gets called repeatedly
due to re-renders of a component, which can lead to slow rendering.
useMemo( ) hook can be used to cache such functions. By using useMemo(
), the CPU-Expensive function gets called only when it is needed.
Using React.PureComponent -
It is a base component class that checks the state and props of a
component to know whether the component should be updated.
Instead of using the simple React.Component, we can use
React.PureComponent to reduce the re-renders of a component
unnecessarily.
Maintaining State Colocation -
This is a process of moving the state as close to where you need it as
possible.
Sometimes in React app, we have a lot of unnecessary states inside the
parent component which makes the code less readable and harder to
maintain. Not to forget, having many states inside a single component
leads to unnecessary re-renders for the component.
It is better to shi states which are less valuable to the parent component,
to a separate component.
Lazy Loading -
It is a technique used to reduce the load time of a React app. Lazy loading
helps reduce the risk of web app performances to a minimum.
return (
<div>
<button onClick={increment}>Increment Counter</button>
<ChildComponent counterValue={counter} />
</div>
);
}
As one can see in the code above, we are rendering the child component inside the
parent component, by providing a prop called counterValue. The value of the counter
is being passed from the parent to the child component.
We can use the data passed by the parent component in the following way:
function ChildComponent(props) {
return (
<div>
<p>Value of counter: {props.counterValue}</p>
</div>
);
}
function ParentComponent(props) {
let [counter, setCounter] = useState(0);
let callback = valueFromChild => setCounter(valueFromChild);
return (
<div>
<p>Value of counter: {counter}</p>
<ChildComponent callbackFunc={callback} counterValue={counter} />
</div>
);
}
As one can see in the code above, we created a function called callback which takes
in the data received from the child component as a parameter.
Next, we passed the function callback as a prop to the child component.
function ChildComponent(props) {
let childCounterValue = props.counterValue;
return (
<div>
<button onClick={() => props.callbackFunc(++childCounterValue)}>
Increment Counter
</button>
</div>
);
}
In the code above, we have used the props.counterValue and set it to a variable called
childCounterValue.
Next, on button click, we pass the incremented childCounterValue to the
props.callbackFunc.
This way, we can pass data from the child to the parent component.
While developing React applications, we might develop components that are quite
similar to each other with minute differences. In most cases, developing similar
components might not be an issue but, while developing larger applications we need
to keep our code DRY, therefore, we want an abstraction that allows us to define this
logic in a single place and share it across components. HOC allows us to create that
abstraction.
Example of a HOC:
Consider the following components having similar functionality. The following
component displays the list of articles:
Notice the above components, both have similar functionality but, they are calling
different methods to an API endpoint.
Let’s create a Higher Order Component to create an abstraction:
Using the concept of Higher-Order Components, we can now render the ArticlesList
and UsersList components in the following way:
Remember, we are not trying to change the functionality of each component, we are
trying to share a single functionality across multiple components using HOC.
Since it is an early time for Hooks, few third-party libraries may not be compatible
with Hooks at present, but they will be added soon.
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.
JSX will permit you for writing HTML-style template syntax directly into the
JavaScript file. This mixture of JavaScript and HTML will be converted by React
toolchain into pure JavaScript that will render the HTML element.
It is possible to define your own React components by writing a function that will
return a JSX element. You can try this by creating a new file src/SearchItem.js and
put the following code into it.
This is all about how you can create a component. It will only display the empty table
and doesn’t do anything. But you will be able to use the Search component in the
application. Open the file src/App.js and add the import statement given below to
the top of the file.
Now, from the logo.svg, import will be removed and then contents of returned value
in the function App() will be replaced with the following code:
<div className="App">
<header>
Items with Hooks
</header>
<SearchItem/>
</div>
You can notice that the element <SearchItem/> has been used just similar to an
HTML element. The JSX syntax will enable for including the components in this
approach directly within the JavaScript code. Your application can be tested by
running the below-given command in your terminal.
npm start
This command will compile your application and open your default browser into
http://localhost:4000. This command can be kept on running when code
development is in progress to make sure that the application is up-to-date, and also
this browser page will be reloaded each time you modify and save the code.
This application will work finely, but it doesn’t look nice as it doesn’t react to any
input from the user. You can make it more interactive by adding a state with React
Hooks, adding authentication, etc.
componentWillMount() {
this.updateDimension()
}
componentDidMount() {
window.addEventListener('resize', this.updateDimension)
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimension)
}
updateDimension() {
this.setState({width: window.innerWidth, height: window.innerHeight})
}
render() {
return <span>{this.state.width} x {this.state.height}</span>
}
}
Also, the functional component AboutPage will obtain the data passed by
props.match.params.aboutId .
A er button click in the HomePage the page will look like below:
Conclusion
React has got more popularity among the top IT companies like Facebook, PayPal,
Instagram, Uber, etc., around the world especially in India. Hooks is becoming a trend
in the React community as it removes the state management complexities.
This article includes the most frequently asked ReactJS and React Hooks interview
questions and answers that will help you in interview preparations. Also, remember
that your success during the interview is not all about your technical skills, it will also
be based on your state of mind and the good impression that you will make at first.
All the best!!
Useful References and Resources:
"Beginning React with Hooks " book by Greg Lim
“Learn React Hooks” book by Daniel Bugl
Node.js vs React.js
React Native Interview Questions
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions
MUKUL
RAJPOOT
WHAT?
Debouncing is a technique that
ensures a function is executed only
after a certain period of inactivity. It
improves efficiency and prevents
unnecessary function calls.
MUKUL
RAJPOOT
STEPS?
1️⃣ Event-Triggered: Start with an event that
you want to handle efficiently, like user
input or scrolling.
MUKUL
RAJPOOT
APPLICATION?
Debouncing is commonly used in
scenarios like autocomplete search,
resizing windows, and handling scroll
events. It helps create smoother user
experiences and optimizes your
applications.
MUKUL
RAJPOOT
EXAMPLE?
EXAMPLE?
In above code, we're using the setTimeout
function to implement a simple
debouncing mechanism. Whenever the
searchTerm state changes, the useEffect
hook sets up a timer to execute the search
logic after a delay of 300 milliseconds.
MUKUL
RAJPOOT
BENEFITS?
Implementing debouncing
techniques in your web development
projects offers several benefits:
Smoother user experiences
Reduced server load
Improved performance
MUKUL
RAJPOOT
FOLLOW
MUKUL RAJPOOT
FOR MORE SUCH
CONTENT
THANKS
100 React
Interview Q&A
Made by Want More
1. What is React?
JSX is a syntax extension used in React that allows you to write HTML-like
code within JavaScript. It provides a convenient way to define the
structure and appearance of React components.
Functional components are simpler and easier to read and test compared
to class components. They don't have their own state or lifecycle methods.
Class components, on the other hand, can manage their own state and
have access to lifecycle methods such as componentDidMount() and
componentDidUpdate().
Props (short for properties) are used to pass data from a parent
component to a child component. Props are read-only and cannot be
modified by the child component. They are passed as attributes to the
child component in JSX.
Keys are used in React lists to give each item a unique identifier. They help
React identify which items have changed, been added, or been removed
in a list, improving performance and avoiding unnecessary re-rendering of
components.
Refs are used in React to get direct access to a DOM element or a React
component instance. They provide a way to interact with the underlying
DOM or component imperatively, outside of the typical React data flow.
React Hooks are functions introduced in React 16.8 that allow you to use
state and other React features in functional components. Hooks provide a
way to use local component state, lifecycle methods, and other React
features without writing a class.
The useMemo() Hook is a built-in Hook in React that memoizes the result
of a computation and returns the cached result when the dependencies
haven't changed. It helps in optimizing performance by avoiding
unnecessary expensive calculations.
24. What is the useReducer() Hook used for?
React Fragments are a feature in React that allows you to group a list of
children without adding extra nodes to the DOM. They are useful when
you need to return multiple elements from a component's render()
method, but they don't need a parent container element.
The useRef() Hook is a built-in Hook in React that provides a way to create
a mutable reference that persists across re-renders of a component. It can
be used to access DOM elements or store mutable values that won't
trigger re-renders.
React context provides a way to pass data through the component tree
without having to pass props manually at every level. It allows you to
create a global state accessible to all components within a context
provider.
The key prop is used in React lists to give each item a unique identifier. It
helps React identify which items have changed, been added, or been
removed in a list, improving performance and avoiding unnecessary re-
rendering of components.
The React Context API provides a way to share data across a component
tree without manually passing props down through every level. It is useful
when you have data that needs to be accessed by multiple components at
different levels in the component hierarchy.
The React DevTools Profiler is a tool used for profiling and optimizing the
performance of React applications. It allows you to analyze and measure
component render times and interactions to identify performance
bottlenecks and optimize your application.
To handle form submissions in React, you can use the onSubmit event
handler on the form element. You can prevent the default form
submission behavior using event.preventDefault() and then access the
form data from the event object to perform further processing or submit
data to a server.