Skip to content

Commit df24e9f

Browse files
committed
react interview question part 1
1 parent 0fc8e22 commit df24e9f

File tree

2 files changed

+287
-0
lines changed

2 files changed

+287
-0
lines changed

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@
2121
npm-debug.log*
2222
yarn-debug.log*
2323
yarn-error.log*
24+
.history

Diff for: src/ReactInterviewQuestionsAnswer.ts

+286
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,286 @@
1+
/*
2+
https://github.com/sudheerj/reactjs-interview-questions/blob/master/README.md#what-is-react
3+
4+
React Interview Questions and answers
5+
6+
Question: What is React?
7+
8+
Answer: React is an open-source javascript library which helps us to make web
9+
and mobile apps. It is used to build user interfaces (UI) on the front end.
10+
It is the view layer of an MVC application (Model view controller).
11+
It support server-side and client-side rendering.
12+
We can easily create custom component and reused at multiple places.
13+
React also streamlines how data is stored and handled using state and props.
14+
15+
Question: What is JSX?
16+
17+
Answer: JSX stands for Javascript XML. It is simply a syntax extension of Javascript
18+
It allows us to directly write HTML in React (within Javascript code).
19+
JSX produce react elements.
20+
After compilation, JSX is always going to get compiled to React.createElement
21+
via Babel.
22+
23+
https://reactjs.org/docs/introducing-jsx.html
24+
https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=false&corejs=3.6&spec=false&loose=false&code_lz=GYVwdgxgLglg9mABAIRFKDEAoDeiCGAJoQGIBOMApmIYgL4CUiOAUIomZVCGUlm-0QAeAEZoMSBAGEANjAgBrALw4ipCtUJ0AfAEFiiclRpCA9GPQJtAhizotQkWJgCqAZ0plseMPgC2lAA0BMRGmvRMrOyc3LzYAuxChDAAbtaCgkIADto4vgF0ZjkJmaiWSGphNCqVGjR0pumZpslpNnYsLELunoj5lEoARPhgIABWg-y1xoQqWExK2n0gMjJ0iI1AA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=env%2Creact%2Cstage-2&prettier=false&targets=&version=7.16.12&externalPlugins=&assumptions=%7B%7D
25+
26+
Question: What is the difference between Element and Component?
27+
28+
Answer:
29+
Element:
30+
A React Element is an object representation of a DOM node. React element
31+
isn't actually the thing you will see on your screen. Instead it is just
32+
an object representation of it.
33+
There are a few reason for this:
34+
Javascript objects are lightweight.
35+
React can create and destroy these elements without too much overhead.
36+
React can easily compare between 2 objects and see what changed.
37+
React can update the actual DOM only where those changes occurred.
38+
It will helps to increase the performance because we only changes what is required.
39+
40+
To create React element, use can use createElement method.
41+
https://reactjs.org/docs/react-api.html#createelement
42+
43+
const element = React.createElement(
44+
'div',
45+
{id: 'login-btn'},
46+
'Login'
47+
)
48+
It takes 3 arguments.
49+
1 - Tag name like div
50+
2 - Attributes you want the element to have. {id: 'login-btn'}
51+
3- The contents or the children of the element. 'Login'.
52+
53+
The createElement return an object that looks like this:
54+
55+
{
56+
type: 'div',
57+
props: {
58+
children: 'Login',
59+
id: 'login-btn'
60+
}
61+
}
62+
63+
When we render this using ReactDOM.render in the DOM, it looks like this:
64+
<div id='login-btn'>Login</div>
65+
66+
Component:
67+
A component is a function or Class which optionally accepts input and return
68+
a React element.
69+
70+
const Button = ({ onLogin }) =>
71+
<div id={'login-btn'} onClick={onLogin}>Login</div>
72+
73+
This JSX get compiled to a React.createElement() function tree:
74+
const Button = ({ onLogin }) => React.createElement(
75+
'div',
76+
{ id: 'login-btn', onClick: onLogin },
77+
'Login'
78+
)
79+
80+
Reference: https://ui.dev/react-elements-vs-react-components/
81+
82+
Question: How to create components in React?
83+
84+
Answer: We can create component in two ways:
85+
86+
Function Component.
87+
88+
function Greeting({ message }) {
89+
return <h1>{`Hello, ${message}`}</h1>
90+
}
91+
92+
Class Component:
93+
94+
class Greeting extends React.Component {
95+
render() {
96+
return <h1>{`Hello, ${this.props.message}`}</h1>
97+
}
98+
}
99+
100+
After 16.8 React version, It is always recommended to use function components
101+
because we can use hooks.
102+
103+
Question: What is state in React?
104+
105+
Answer: State is a plain javascript object that holds some information
106+
that may change over the lifetime of the component. It is managed in the
107+
component (Just like any variable declared in a function). When state changes,
108+
the component responds by re-rendering.
109+
110+
Example:
111+
function Counter({initialCount}) {
112+
const [count, setCount] = useState(initialCount);
113+
return (
114+
<>
115+
Count: {count}
116+
<button onClick={() => setCount(initialCount)}>Reset</button>
117+
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
118+
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
119+
</>
120+
);
121+
}
122+
123+
https://reactjs.org/docs/faq-state.html
124+
125+
Question: What is props in React?
126+
127+
Answer: Props are input to components (similar to function parameters). Props
128+
can be single values or objects containing a set of values that are passed
129+
to the component.
130+
Props holds information and When props changed, the component responds by
131+
re-rendering.
132+
Props are passed from parent component to child component.
133+
134+
Function component:
135+
136+
function Welcome(props) {
137+
return <h1>Hello, {props.name}</h1>;
138+
}
139+
140+
Class component:
141+
142+
class Welcome extends React.Component {
143+
render() {
144+
return <h1>Hello, {this.props.name}</h1>;
145+
}
146+
}
147+
148+
<Welcome name="Sara" />
149+
150+
Question: What is the difference between state and props?
151+
152+
Answer: Props and state are plain javascript objects.
153+
Both holds the information
154+
Both props and state changes trigger a render update.
155+
Props get passed to the component same like Function parameters. Component
156+
can not change its props.
157+
State is managed within component same like variable declared within a function.
158+
Component can change its state.
159+
160+
Question: What are inline conditional expressions?
161+
162+
Answer: We can use inline conditional expression in JSX to render UI elements.
163+
we can use with curly braces {} and use JS logical operator &&
164+
165+
{isFetching && <Spinner>}
166+
{isFetching ? <Spinner> : <h1>Comments</h1>}
167+
You have {messages.length} unread messages.
168+
169+
Question: What is "key" prop and what is the benefit of using it in arrays of
170+
elements?
171+
172+
Answer: A key is a special string attribute we should include when creating
173+
arrays of elements. Key prop help react identify which items have changes,
174+
are added or are removed.
175+
React show warning message in the console if we don't add key prop is not
176+
present in the array of list.
177+
178+
const todoItems = todos.map((todo) =>
179+
<li key={todo.id}>
180+
{todo.text}
181+
</li>
182+
)
183+
Youtube video to learn more: https://youtu.be/AMlJdo0urYM
184+
185+
Question: How to create refs and use of refs?
186+
187+
Answer: React ref helps us to manage the reference a DOM element. This give
188+
us the ability to modify or change the element or an instance of a component.
189+
We can access elements/components without state updates or rerenders.
190+
191+
As per the react documentation we should only use ref for these three possible
192+
use cases:
193+
194+
- Managing focus, text selection or media playback.
195+
Ref help us to interact with the DOM API and perform actions like
196+
getting value from the input element, focus the input or manage media element.
197+
198+
- Imperative animations
199+
It require access to the responsible DOM node to manipulate the target elements.
200+
Ref attributes provide access of the elements at different part of the app.
201+
202+
- Integrating with third-party DOM libraries:
203+
Some library need DOM element access to perform operations like map, editors,
204+
image manipulation tools, etc. These component need DOM element access and
205+
we use ref for it.
206+
207+
function TextInputWithFocusButton() {
208+
const inputEl = useRef(null);
209+
const onButtonClick = () => {
210+
inputEl.current.focus();
211+
};
212+
return (
213+
<>
214+
<input ref={inputEl} type="text" />
215+
<button onClick={onButtonClick}>Focus the input</button>
216+
</>
217+
);
218+
}
219+
220+
Youtube video for reference: https://youtu.be/1rfxnJ38dWY
221+
222+
Question: What are forward refs?
223+
224+
Answer: Forward ref helps to pass ref through a component to one of its
225+
children.
226+
227+
const FancyButton = React.forwardRef((props, ref) => (
228+
<button ref={ref} className="FancyButton">
229+
{props.children}
230+
</button>
231+
));
232+
233+
const ref = React.createRef();
234+
<FancyButton ref={ref}>Click me!</FancyButton>;
235+
236+
Component using FancyButton can get a ref to the button DOM node and access
237+
it if necessary.
238+
239+
Question: What is Virtual DOM and how it works?
240+
241+
Answer: DOM -> document object model.
242+
It is a structured representation of the html elements that are present
243+
in the web app. DOM represent the entire UI of your app. The DOM is
244+
represented as a tree data structure. We can easily update the content in
245+
the dom with javascript.
246+
247+
const element = document.getElementById('some-id');
248+
element.innerValue = 'updated value';
249+
250+
We can easily access the dom element with the help of `getElementById()` javascript
251+
function. When we make changes in the app state it will update the UI.
252+
253+
The problem come when we need to update the large application which has 1000
254+
elements in the UI.
255+
If we make any changes then DOM will update and UI components have to be
256+
re-rendered.
257+
When we update the dom, then these things happen:
258+
259+
- The browser parse the HTML to find the node with ID.
260+
- It remove the child element of specific element.
261+
- Update the DOM element with the new value
262+
- Recalculates the CSS for the parent and child nodes.
263+
- Update the layout.
264+
- Finally, update the UI in the browser.
265+
266+
If you see, there are lot of things happen when we directly change in the UI.
267+
268+
Virtual DOM - It is lightweight Javascript object which is copy of Real DOM.
269+
270+
Updating virtual DOM in ReactJs is faster because ReactJs uses:
271+
- Efficient diff algorithm.
272+
- Batched update operation.
273+
- Efficient update of subtree.
274+
275+
When we call setState() or update state, component rerender. Reactjs creates
276+
the whole virtual DOM from scratch.
277+
React maintains two virtual DOM, one with the updated state virtual DOM and
278+
other with the previos state virtual dom.
279+
React use diff algorithm compare both the virtual dom to find the minimum number
280+
of steps to update the real dom.
281+
282+
Reference:
283+
https://medium.com/@happymishra66/virtual-dom-in-reactjs-43a3fdb1d130
284+
https://www.geeksforgeeks.org/reactjs-virtual-dom/
285+
286+
*/

0 commit comments

Comments
 (0)