Advanced React Interview

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

A. 7 common advanced React.

js interview questions
1. How do you create refs in React ?
2. Name three advantages of using React Hooks
3. Name two advantages of using React.js
4. Outline the different stages of the React.js lifescycle
5. What happens if you attempt to update the state directly ?
6. Explain whether Hooks replace higher-order components.
7. Name one advantage of using Flux
B. 8 advanced behavioral React.js interview questions
1. Which method would you use to handle events in React ?
2. In which situation would you use refs in React ?
3. Why would you use super constructors with props arguments ?
4. How would you use validation on props ?
5. Which method would you use to add attributes to components conditionally ?
6. What methods would you use to check and improve slow app rendering in React ?
7. In which situation would you use useMemo() in React ?
8. How would you avoid binding in React?
C. 28 advanced React.js interview questions about definitions and terms
1. Explain what a higher-order component is.
2. Explain what a mounted component is.
3. Explain what useState is.
4. Explain what an event in React
5. What is a class component ?
6. What is a component ?
7. What is the different between class and functional components ?
8. What is a state object ?
9. What is a props object ?
10. How are state object different from props objects ?
11. Explain what MVC architecture is .
12. Name an architectural difference between React and Angular.
13. Explain what a controlled component is.
14. Explain what an uncontrolled component is.
15. How are controlled and uncontrolled components different ?
16. Explain what React Hooks are.
17. Explain what three dots mean in React
18. What are package managers in React.js
19. Explain what prop drilling is
20. Explain what StrictMode is
21. Explain what the Shadow DOM is
22. Explain what the virtual DOM is
23. How is the Shadow DOM different from the virtual DOM ?
24. Explain what the React.js lifecycle methods are
25. Explain what a pure function is
26. Explain what JSX is
27. Explain what Flux architecture is.
28. What are bundlers in React.js?
29. What is the difference between Element and Component ?
30. What are react fragments ?
31. Why should component names start with capital letters ?
32. What are the reasons why browsers don’t support JSX ?
33.
Trả lời
A. 9 common advanced React interview questions
1. How do you create refs in React ?
- Creating refs in React very simple. Refs are generally used for the following purpose:
o Managing focus, text section, or media playback.
o Triggering imperative animations.
o Integrating with third-party DOM libraries.
- Note: You should avoid using refs for anything that can be done declarratively.
 Method 1: Using React.createRef().
o Create a ref variable using React.createRef()
o Use the element’s ref attribute to attach the ref variable
 Method 2: Using useRef() hook
o Create a ref variable using React.useRef()
o Use the element’s attribute to attach the ref variable
o The benefit of using useRef() over createRef() is that it’s handy for keeping
any mutable value around similar to how you’d use instance fields in classes.
o useRef() also takes an initial value
 Method 3: Using callback ref
o Creating ref using this method is a bit different than the other two methods.
Instead of passing a ref attribute created using createRef() or useRef() we
pass a function. The function receivers the React element or HTML DOM
element as an argument, which can be used.
2. Name two advantages of using React.js
- Speed: React basically allows developers to utilize individual parts of their application on
both the client-side and the server-side, which ultimately boosts the speed of the
development process.
- Flexibility: Compared to other front-end framework like Angular, Vue…, the React code
is easier to maintain and is flexible due to its modular structure. This flexibility, in turn,
saves a huge amount of time and cost to businesses.
- Performance: React JS was designed to provide high performance. The core of the
framework offers a virtual DOM program and server-side rendering, which makes
complex applications run extremely fast.
- Usability: Deploying React is faily easy to accomplish if you have some knowledge of
Javascript.
- Reusable: One of main benefits of using React JS is its potential reuse components. It
saves time for developers as they dont’t have to write various code for the same
features. Furthermore, if any change are made in any particular part, will not affect
other parts of the application.
3. Name three advantages of using React Hooks ?
- Three advantages of using Reat Hooks are that they enable developers to:
o Enhance component tree readability
o Share logic among different components
o Effectively handle the setup of side-effects.
4. Outline the different stages of the React.js lifecycle.
- Mount: Creating component
o When React create or render component for the first time, it’s the first
mounting. That means it’s be added to the DOM and React will keep track of it.
o I like imagine mounting as a new box be added inside its parent.
o Mounting happens whenever component hasn’t been rendered and its parent
decides to render it for the first time. In other words, mounting is a component
being “born”
o A component can be created and destroyed many times and each time it’s
created, it will be mounted again.
o One a component is mounted, it will do a few things:
 Initialize useState with default values: this only happens on mount.
 Execute the component’s logic
 Do an initial render, adding the elements to the DOM
 Run the useEffect hook
o Note that useEffect hook run after initial render. It’s the time you want run code
like a create even handlers, executing heavy logic or fetch data.
- Render: Updating what the user sees
o After a component mounted, any change for props or state will make it re-
render, execute again all of code inside its, include children componnents. After
each “render” the useEffect hook is evaluated gain.
o Once a component’s parent decides to stop rendering a child – because of a
onditional, changes in data or any other reason – the component will need to be
unmounted.
- Unmounting: Deleting components
o When a component is unmounted React will remove it from the DOM and stops
keeping track of it. The component is deleted including any state it had.
o Like explained in the mounting phase, a component is both mounted and
unmounted by its parent, and if the component, in turn, has children it will
unmount those too, and the cycle repeats until the last child is reached.
5. What happens if you attempt to update the state directly ?
- When you try to update state directly then it won’t re-render the component.
6. Explain whether Hooks replace higher-order components
7. Name one advantage of using Flux

7 Advanced behavioral React JS interview questions

1. Which method would you use to handle events in React ?


- Handling events in React, you would name them using camelcase (instead of lowercase).
When you use JSX, they pass a function as the event handle (instead of a string).
2. In which situation you use refs in React ?
- When I want to focus point like a input, text or media playback.
- When use node DOM to interact with 3rd party library
- When active a animation
3. Why would you use super constructors with props arguments ?
-
4. How would you use validation on props ?
- Props be used to passing read-only attributes to React component. For the proper
functioning of components and to avoid future bugs and glitches it is necessary that
props are passed correctly. Hence, using validation on props is required to improving
React performance.
- React JS has an inbuilt feature to validating props data type to make sure that values
passed through props are valid. React components have a property called propTypes
which is used to setup data type validation.
5. Which method would you use to add attributes to components conditionally ?
- Using if-else statements is one of the easiest ways to implement conditional attributes.
It is pretty much straightforward and readable.
- The ternary operator is an inline conditional operator which takes three arguments. It
allows us to wrap our conditions to a single line where the first argument will be a
condition.
- The usage of && operator is much similar to previous ternary approach. && is a logical
operator that allows a condition on the left side and output on the right-side.
- Spread operator is one of my favorites when it comes to conditional props. The spread
operator is used when passing all the properties of an object or all the elements of an
array to React Component.
6. What methods would you use to check and improve slow app rendering in React ?
- React has gained significant popularity as a library for building Uis on the web. One of
the main attractors the the library is its impressive browser performance, thanks to its
implementation of a virtual DOM.
- When working on small projects, you shouldn’t run into many issues. However, larger
projects will typically have more complex UI components, process more data and
generally have more moving parts. All of these factors can impact the performance of
your app.
- Three approaches to check (measuring) React performance:
o Using the Chrome DevTools Performance tab
o Using the React Developer Tools Chrome Extension
o Using React’s Profiler API
- 11 proven ways to improve & boost React Performance
o Windowing or List virtualization in React Application
o Key Coordination for List Rendering
o Lazy loading images in React
o Functional Components & Component Interaction
o Understand How to Handle “this”
o Use a Function in setState
o Utilize prop-Types
o Trim javascript Bundles
o Server-side rendering (SSR)
o React Redux Optimization Tips
o Improve React App performance using React Memo [Memoization]
7. In which situation would you use useMemo() in React ?
- Using useMemo() to cache a variable’s value along with dependency lists ?
- Using useMemo() to help them avoid unnecessary re-renders .
- Using useMemo() can be useful in situations where there are high processing amounts.

28 advanced ReactJS interview questions about definitions and terms

1. Explain what a higher-order component is.


- A Higher Order Component (HOC) is a component that receives another component.
The HOC contains certain logic that we want to apply to the compoent that we pass as a
parameter. After applying that logic, the HOC returns the element with the additional
logic.
2. Explain what a mounted component is.
- Mounting is the initial phases in which the instance of the component is created and
inserted into the DOM. When the component gets successfully inserted into the DOM,
the component is said to be mounted.
3. Explain what useState is.
- useState() is a hook in React allows you to have state variables in functional
components. So basically useState is the ability to encapsulate local state in a functional
component
4. Explain what an handling events is in React
- Handling events with React elements is very similar to handling events on DOM
elements. There are some syntax differences:
o React events are named using camelCase, rather than lowercase
o With JSX you pass a function as the event handler, rather than a string.
5. What is a class component ?
- React class based components are the bread and butter of most modern web apps built
in ReactJS. These components are simple classes (made up of multiple functions that
add functionality to the application). All class based components are child classes for the
Component class of ReactJS.
6. What is a component ?
- Components are independent are reusable bits of code. They serve the same purpose as
Javascript functions, but work in isolation and return HTML. Components come in two
types, Class Components and Function components.
7. What is the difference between class and functional components ?

Functional Components Class Components


A functional component is just a plain A class component requires you to extend
Javascript pure function that acceps props from React. Component and create a
as an argument and returns a React render function which returns a React
element (JSX) element.

There is no render method used in It must have the render() method


functional components. returning JSX (which is syntactically similar
to HTML)
Functional component run from top to Class component is instantiated and
bottom and once the function is returned different life cycle method is kept alive and
it can’t be kept alive. being run and invoked depending on
phase of class component.
Also known as Stateless components as Also known as Stateful component
they simply accept data and display them because they implement logic and state.
in some form, that they are mainly
responsible for rendering UI
React lifecycle methods (for example, React lifecycle methods can be used inside
componentDidMount) cannot be used in class components (for example,
functional components. componentDidMount)
Hooks can be easily used in functional It requires different syntax inside a class
components to make them Stateful. component to implement hooks.

Example: const [name,setName] = Example: constructor(props) {


React.useState(“”) Super(props);
This.state = {name:””}
}
Constructors are not used Constructor are used as it needs to store
state.

8. What is a state object ?


- React Components has a built-in state object.
- The state object is where you store property values that belongs to the component.
- When the state object changes, the component re-renders.
9. What is a props object ?
- In React, the term props stands for properties, which refers to the properties of an
object. This is because all elements created in React are Javascript objects. As a results,
Passing data into a component is a done by creating properties and values for the
object.
10. How are state objects different from props objects ?

PROPS STATE
The data is passed from one component to The data is passed within the component
another only.
It is Immutable (cannot be modified ) It is Mutable (can be modified)
Props can be used with state and State can be used only with the state
functional components. components / class component.
Props are read-only. State is both read and write.
11. Explain what MVC architecture is.
- The Model-View-Controller (MVC) framework is an architectural/ design pattern that
separates an application into three main logical components Model, View and
Controller. Each architectural component is built to handle specific development aspects
of an application. Each architectural component is built to handle specific development
aspects of an application. It isolates the business logic and presentation layer from each
other. It was traditionally used for desktop graphical user interfaces (GUIs). Nowadays,
MVC is one of the most frequently used industry – standard web development
framework to create scalable and extensible projects. It is also used for designing mobile
apps.
12. Explain what Flux architecture is.
- Flux Architecture:
o Flux is an architecture that Facebook uses internally when operating with React.
o It is not a framework or a library.
o It is merely a replacement quite an architecture that enhances React and also
the idea of unidirectional data flow.
13. Name an architectural difference between React and Angular
- Angular JS is an open-source platform developed by Google, while ReactJS is an open-
source library developed by Facebook.
- Angular JS is Typescript-based web application framework, whereas ReactJS is a
Javascript-based library.
- While talking about ReactJS and Angular, Angular is a JS framework built using
Typescript, whereas ReactJS is a JS library using JSX.
- ReactJs is mostly used to build interactive UI components with frequently variable data,
whereas Angularjs is used to build complex enterprise apps like progressive web apps
and single-page-apps.
- While comparing AngularJS vs ReactJS, Angular JS is used to build single-page
applications using HTML and Typescript. ReactJS is commonly used to create user
interfaces for single-page applications from isolated components.
- The actual difference between React and Angular is their learning curve – Angular is
steeper while React has moderate learning curve.
14. Explain what a controlled component is
- In React, Controlled components are those in which form’s data is handled by the
component’s state. It takes its current value through props and makes changes through
callbacks like onClick, onChange, etc. A parent component manages its own state and
passes the new values as props to the controlled component.
- Example: We are creating a simple form that comprises an input field with a label name
and a submit button. We are creating an onSubmit function that triggers when we
submit the form which shows the name that we have filled in the alert box. We are
creating a state name that stores the value we enter into the input field using the
useState hook. We are creating an onChange function in the input field that stores the
data we are entering in the input field to our state. There is another function
handleSubmit that gets triggered when we submit the form and it shows the name we
have entered on the alert box.
-
15. Explain what an uncontrolled component is.
- Uncontrolled components are the components that are not controlled by the React
state and are handled by the DOM. So in order to access any value that has been
entered we take the help of refs.
- For instance, if we want to add a file as an input, this cannot be controlled as this
depends on the browser so this is an example of an uncontrolled input.
16. How are controlled and uncontrolled components different ?

Controlled Component Uncontrolled Component


The component is under control of the Components are under the control of DOM.
component’s state.
These components are predictable as are Are uncontrolled because during the life cycle
controlled by the state of the component. methods the data may loss.
Internal state is not maintained. Internal state is maintained
It accepts the current value as props We access the values using refs
Does not maintain its internal state. Maintains its internal state.
Controlled by the parent component Controlled by the DOM itself.
Have better control on the form data and values Has very limited control over form values and
data.

17. Explain what React Hooks are


- React Hooks are simple Javascript functions that we can use to isolate the reusable part
from a functional component. Hooks can be stateful and can manage side-effects.
- React provides a bunch of standard in-built hooks:
o useState: to manage states. Returns a stateful value and an updater function to
update it.
o useEffect: to manage side-effects like API calls, subscriptions, timers, mutations,
and more.
o useContext: to return the current value for a context.
o useReducer: a useState alternative to help with complex state management.
o useCallback: It returns a memorized version of a callback to help a child
component not re-render unnecessarily.
o useMemo: It return a memoized value that helps in performance optimizations.
o useRef: It returns a ref object with a current property. The ref object is mutable.
It is mainly used to access a child component imperatively.
o useLayoutEffect: It fires at the end of all DOM mutations. It’s best to use
useEffect as much as possible over this one as the useLayoutEffect fires
synchronously.
o useDebugValue: helps to display a label in React DevTools for custom hooks.
18. Explain what three dots mean in React
- The three dots (…) notation referred to as the Spread syntax has been part of React for a
long time when it could be used via transpilation, although, it has been made a part of
Javascript as part of the ES2015 syntax.
- The Spread syntax is used to deconstruct an array or object into separate variables
where the exact number of elements in the array may not be known or when we wish to
keep an attribute or a separate from the entire object.
- The following can be performed usign the spread syntax:
o Passing attribute: an object can directly be passed to a component instead of
passing each data value in the object separately.
o Extend an object: When creating a new object that inherits another object, we
can use the Spread syntax to inherit parent object.
o Concatenate arrays: we can also concatenate arrays using Spread syntax
o Destructuring Arrays: Destructuring an array into separate components can also
be performed using the spread syntax
19. What are package managers in React
- Package managers are tools that help software developers to easily share software
libraries and manage dependencies, escpecially transitive type dependencies. Every
software developer uses a specific package manager for downloading the software he or
she will be using.
- A package manager contains two parts, the repository or database which contains the of
binaries or source code, as well as, the client which communicates with the repository
and performs some work on the client side.
- In most cases this a command line tool not a user interface.
- The advantages of such a system are quite obvious, it is easier to stay in control of
dependencies if you are only required to change a number in a text file and execute a
command.
- The package manager does everything for you and you won’t need to check in the actual
software libraries into your SCM. You only check-in the project file from your package
manager.
20. Explain what prop drilling is.
- Prop drilling is a situation where data is passed from one component through multiple
interdependent components until you get to the component where the data is needed.
21. Explain what StrictMode is
- React’s StrictMode is sort of a helper component that will help you write better React
components, you can wrap a set of components with <StrictMode/> and it’ll basically:
o Verify that the components inside are following some of the recommend
practices and warn you if not in the console.
o Verify the dprecated methods are not being used, and if they’re used strict
mode will warn you in the console.
o Help you prevent some side effects by identifying potential risks.
- As the coumentation says, strict mode is development oriented so you don’t need to
worry about it impacting on your production build.
- I’ve found it especially useful to implement strict mode when I’m working on new code
bases and I want to see what kind of code/components I’m facing. Also if you’re on bug
hunting mode, sometimes it’s a good idea to wrap with <StrictMode/> the
components/blocks of code you think might be the source of the problem.
22. Explain what the Shadow DOM is
- Shadow DOM, on the other hand, relates mostly to the concept of encapsulation. It is
tool that allows developers to overcome DOM encapsulation.
- It refers to potential of browser to add a subtree of DOM elements into rendering of
document, but not into DOM tree of main document.
- Thus, it isolates DOM and ensures that a component’s DOM is separate element that
will not appear in a global DOM
- Contrary to the DOM, shadow DOM occurs in smaller pieces, implying that (unline the
Virtual DOM) it is not a complete representation of the entire DOM.
- It is also proven to be helpful with CSS scoping. The styles used in an application can
overlap which makes it cumbersome to handle them. Shadow DOM ensures t hat the
styles created inside a single Shadow DOM element remain isolated and within their
own scope
23. Explain what the virtual DOM is
- Virtual DOM, in simple terms, is nothing but the complete and full representation of an
actual DOM
- Since any changes to the DOM causes the page to re-render more often than not, Virtual
DOM primarily attempts to avoid any unnecessary and expensive changes to the DOM
- This is achieved by grouping changes and doing a single re-render instead of several
small ones.
- A copy of the DOM is saved in memory and is used to compare any change being done
anywhere in the DOM, it is compared to find differences. Thus, only those parts of the
application are re-rendered which are updated instead of re-rendering the entire DOM.
- VueJS and ReactJS both use virtual DOM
24. How is the Shadow DOM different from the virtual DOM ?

Virtual DOM Shadow DOM


It resolves around solving performance issues It resolves around the concept of
encapsulation.
It is a complete representation of an actual It is not a complete representation of the
DOM entire DOM
It groups together several changes and does a It adds a subtree of DOM elements into the
single re-render instead of many small ones. rendering of a document, instead of adding it
to the main document’s DOM tree.
It creates a copy of the whole DOM object It creates small pieces of the DOM object
having their own, isolated scope.
It does not isolate the DOM It isolates the DOM
It does not help with CSS scoping It helps with CSS scoping.

25. Explain what the React.js lifecycle methods are.


- With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as
well as the state in the functional Components. Currently, useEffect hook can be used to
replicate lifecycle behavior, and useState can be used to store state in a function
component.
- useEffect can also return a function that will be run when the component is unmounted.
This can be used ti unsubcribe to listeners, replicating the behavior of
componentWIllMount
26. Explain what JSX is
- JSX is basically a syntax extension of regular JavaScript and is used to create React
elements. These elements are then rendered to the React DOM. We will learn about
rendering and DOM in the next article in detail.
- JSX stands for JavaScript XML
- JSX allows us to write HTML in React.
- JSX makes it easier to write and add HTML in React.
- Why JSX ?
o JSX helps us in keeping our code simpler and elegant when writing large pieces
of code
o According to the React docs, most people find it helpful as a visual aid when
working with user interface inside JavaScript code.
o JSX also allows React show error and warning messages more useful.
o If one is familiar with HTML, it is quite easy to use JSX when building React
application
o Faster than normal JavaScript as it performs optimizations while transpiling to
regular Javascript.
27. Explain what a pure function is
- Pure function is is a function (a block of code) always return same result if the same
arguments are passed. It does not depend on any state or data change during a
program execution. Rather, it only depends on its input arguments.
- Also, a pure function does not produce any observable side effects such as network
requests or data mutation,etc.
28. What are bundlers in React.js
- Module bundler đã được sinh ra như thế nào ?
o Nếu đã từng làm front-end developer, hẳn đã từng ít nhất một lần làm việc với
webpack, rollup, parcel, @babel/core... và bạn có biết tất cả các bạn này có tên
chung là gì không ? là module bundler đó.
- Chuyện làm web thời xưa
o Thời xưa, người ta chẳng cần bundler gì hết. Câu chuyện này giống như chuyện
thời xưa người ta không cần điện thoại ấy.
o Để xây dựng một trang web, cần các nguyên liệu chính là HTML,CSS và JS. Điều
này nghe đơn giản và dễ hiểu đúng không ?
- Chuyện làm web thời nay
o Còn thời nay, chẳng ai build website với chỉ HTML,CSS ,JS cả. Ít nhất ấy, thì cũng
có một vài thứ khác bổ trợ như html-inspector, jQurey, React, Angular,... và còn
nhiều loại module javascript khác nữa.
o Còn chưa kể app script không chỉ là một file là xong logic cho cả trang web được,
dev cần tách ra nhiều files để dễ quản lý code hơn, như là theo từng thành phần
của trang web hẳng hạn: script-header.js, script-footer.js, script-about-page.js,...
- Bundler ra đời
o Chính vì sự đa dạng và phong phú của các modules được sử dụng ngày càng
nhiều, và sự dính chùng vào nhau khi mô đun A dùng code của mô đun B rồi mô
đun C dùng Code của mô đun D, nên bundler mới được ra đười.
o Nhiệm vụ chính của bundler là gom hết tất cả các loại script lại cùng nhau theo
thứ tự ưu tiên mà bạn đặt cho tụi nó và cho ra một file script duy nhất.
o Chưa kể, nếu bạn không muốn xài javascript nữa, mà muốn xài typescript? Cũng
ok luôn:
 Không muốn xài HTML mà xài React ? Tui ok lên
 Không muốn xài CSS mà xài SASS ? Tui cũng ok luôn
 Chưa hết, bundler còn bao trọn gói các loại modules khác như là lodash,
firebase,...

- Cái khó của bundler:


o Tuy nhiên, vì sự rối rắm của người dùng là dùng quá nhiều các thể loại module
như thế. Thì để tui làm đúng theo được ý của abnjm thì bạn cần cực một xíu.
o Cái cực ở đây là bạn cần config, để bundler biết bạn muốn cái mô đun nào chạy
trước
o VÍ dụ về file webpack.config.js:

29. A
30. B
31. Why browser don’t support JSX ?
- Only Javascript Object be supported by browser, but JSX is not one of them. For this
reason, JSX files must first be converted into Javascript Object like a babel before being
sent to the browser.

You might also like