300 React Js Interview Q&A
300 React Js Interview Q&A
The main principle of this extension was to make front-end code easier
to understand and to help avoid cross-site scripting attacks. The
project was successful to prevent the malicious content submitted by
the scrubbing user.
But there was a different problem with XHP in which dynamic web
applications require many roundtrips to the server, and XHP did not
solve this problem. Also, the whole UI was re-rendered for small
change in the application. Later, the initial prototype of React is
created with the name FaxJ by Jordan inspired from XHP. Finally after
sometime React has been introduced as a new library into JavaScript
world.
3. What is JSX?
JSX stands for JavaScript XML and it is an XML-like syntax extension to
ECMAScript. Basically it just provides the syntactic sugar for
the React.createElement(type, props, ...children) function, giving us
expressiveness of JavaScript along with HTML like template syntax.
In the example below, the text inside <h1> tag is returned as JavaScript
function to the render function.
export default function App() {
return (
<h1 className="greeting">{"Hello, this is a JSX Code!"}</h1>
);
}
If you don't use JSX syntax then the respective JavaScript code should
be written as below,
See Class
<div id="login-btn">Login</div>
iv. Class Components: You can also use ES6 class to define a
component. The above function component can be written as a
class component:
But even there are two reasons to use Class components over Function
components.
The usage of Error boundaries from the above library is quite straight
forward.
But at the same time, it won't compare the previous state with the
current state because function component itself prevents the
unnecessary rendering by default when you set the same state again.
In the above code, the email prop has not been passed to child
component. So there won't be any re-renders for email prop change.
function User() {
const [message, setMessage] = useState("Welcome to React world");
return (
<div>
<h1>{message}</h1>
</div>
);
}
See Class
This reactProp (or whatever you came up with) attribute name then
becomes a property attached to React's native props object which
originally already exists on all components created using React library.
props.reactProp
The properties from props object can be accessed directly using destructing
feature from ES6 (ECMAScript 2015). The above child component can be
simplified like below.
See Class
//Wrong
this.state.message = "Hello world";
<button onclick="activateLasers()"></button>
<button onClick={activateLasers}>
xiii. Public class fields syntax: If you don't like to use bind
approach then public class fields syntax can be used to correctly
bind callbacks. The Create React App enables this syntax by
default.
xvii. handleClick() {
xviii. console.log('SingOut triggered');
xix. }
xx. render() {
xxi. return <button onClick={() =>
this.handleClick()}>SignOut</button>;
}
Apart from these two approaches, you can also pass arguments to a
function which is defined as arrow function
function BookStore() {
handleTitleChange(e) {
console.log('The new title is:', e.target.value);
// 'e' represents synthetic event
const nativeEvent = e.nativeEvent;
console.log(nativeEvent);
e.stopPropogation();
e.preventDefault();
}
Keys should be unique among its siblings. Most often we use ID from
our data as key:
When you don't have stable IDs for rendered items, you may use the
item index as a key as a last resort:
Note:
You can also use refs in function components using closures. Note:
You can also use inline ref callbacks even though it is not a
recommended approach.
render() {
return <div />;
}
}
render() {
return <div ref={this.node} />;
}
}
ii. They are not composable — if a library puts a ref on the passed
child, the user can't put another ref on it. Callback refs are
perfectly composable.
iii. They don't work with static analysis like Flow. Flow can't guess
the magic that framework does to make the string ref appear
on this.refs, as well as its type (which could be different).
Callback refs are friendlier to static analysis.
iv. It doesn't work as most people would expect with the "render
callback" pattern (e.g. )
from documentation
handleSubmit(event) {
alert("A name was submitted: " + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
{"Name:"}
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
iv. Render The component will render without any side effects. This
applies to Pure components and in this phase, React can pause,
abort, or restart the render.
React 16.3+
function HOC(WrappedComponent) {
return class Test extends Component {
render() {
const newProps = {
title: "New Header",
footer: false,
showFeatureX: false,
showFeatureY: true,
};
ReactDOM.render(
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>,
node
);
39. How to write comments in React?
The comments in React/JSX are similar to JavaScript Multiline
comments but are wrapped in curly braces.
Single-line comments:
<div>
{/* Single-line comments(In vanilla JavaScript, the single-line
comments are represented by double slash(//)) */}
{`Welcome ${user}, let's play React`}
</div>
Multi-line comments:
<div>
{/* Multi-line comments for more than
one line */}
{`Welcome ${user}, let's play React`}
</div>
Passing props:
render() {
// no difference outside constructor
console.log(this.props); // prints { name: 'John', age: 42 }
}
}
The above code snippets reveals that this.props is different only within
the constructor. It would be the same outside the constructor.
handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
render() {
// Wrong: handleClick is called instead of passed as a reference!
return <button onClick={this.handleClick()}>{'Click Me'}</button>
}
render() {
// Correct: handleClick is passed as a reference!
return <button onClick={this.handleClick}>{'Click Me'}</button>
}
Now you can import the module using lazy function as below,
function StoryBook() {
return stories.map(story =>
<Fragment key={ story.id}>
<h2>{story.title}</h2>
<p>{story.description}</p>
<p>{story.date}</p>
</Fragment>
);
}
i. Fragments are a bit faster and use less memory by not creating
an extra DOM node. This only has a real benefit on very large
and deep trees.
ii. Some CSS mechanisms like Flexbox and CSS Grid have a special
parent-child relationships, and adding divs in the middle makes it
hard to keep the desired layout.
iii. The DOM Inspector is less cluttered.
ReactDOM.createPortal(child, container);
return (
<>
<button onClick={handleIncrement}>Increment</button>
<span>Counter: {count}</span>
</>
)
}
See Class
i. PropTypes.number
ii. PropTypes.string
iii. PropTypes.array
iv. PropTypes.object
v. PropTypes.func
vi. PropTypes.node
vii. PropTypes.element
viii. PropTypes.bool
ix. PropTypes.symbol
x. PropTypes.any
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
);
}
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>{"Something went wrong."}</h1>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
i. render()
ii. hydrate()
iii. unmountComponentAtNode()
iv. findDOMNode()
v. createPortal()
i. renderToString()
ii. renderToStaticMarkup()
For example, you generally run a Node-based web server like Express,
Hapi, or Koa, and you call renderToString to render your root
component to a string, which you then send as response.
// using Express
import { renderToString } from "react-dom/server";
import MyPage from "./MyPage";
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
{
todos.map((todo, index) => <Todo {...todo} key={index} />);
}
If you use element data for unique key, assuming todo.id is unique to
this list and stable, React would be able to reorder elements without
needing to reevaluate them as much.
{
todos.map((todo) => <Todo {...todo} key={todo.id} />);
}
65. Is it good to
use setState() in componentWillMount() method?
Yes, it is safe to use setState() inside componentWillMount() method. But
at the same it is recommended to avoid async initialization
in componentWillMount() lifecycle method. componentWillMount() is invoked
immediately before mounting occurs. It is called before render(),
therefore setting state in this method will not trigger a re-render. Avoid
introducing any side-effects or subscriptions in this method. We need
to make sure async calls for component initialization happened
in componentDidMount() instead of componentWillMount().
componentDidMount() {
axios.get(`api/todos`)
.then((result) => {
this.setState({
messages: [...result.data]
})
})
}
66. What will happen if you use props in initial
state?
If the props on the component are changed without the component
being refreshed, the new prop value will never be displayed because
the constructor function will never update the current state of the
component. The initialization of state from props only runs when the
component is first created.
this.state = {
records: [],
inputValue: this.props.inputValue,
};
}
render() {
return <div>{this.state.inputValue}</div>;
}
}
this.state = {
record: [],
};
}
render() {
return <div>{this.props.inputValue}</div>;
}
}
For example,
@setTitle("Profile")
class Profile extends React.Component {
//....
}
/*
title is a string that will be set as a document title
WrappedComponent is what our decorator will receive when
put directly above a component class as seen in the example above
*/
const setTitle = (title) => (WrappedComponent) => {
return class extends React.Component {
componentDidMount() {
document.title = title;
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
Note: Decorators are a feature that didn't make it into ES7, but are
currently a stage 2 proposal.
ReactDOMServer.renderToString(<App />);
This method will output the regular HTML as a string, which can be
then placed inside a page body as part of the server response. On the
client side, React detects the pre-rendered content and seamlessly
picks up where it left off.
# Installation
$ npm install -g create-react-app
i. constructor()
ii. static getDerivedStateFromProps()
iii. render()
iv. componentDidMount()
i. componentWillMount()
ii. componentWillReceiveProps()
iii. componentWillUpdate()
This lifecycle method along with componentDidUpdate() covers all the use
cases of componentWillReceiveProps().
This lifecycle method along with componentDidUpdate() covers all the use
cases of componentWillUpdate().
also
i. static methods
ii. constructor()
iii. getChildContext()
iv. componentWillMount()
v. componentDidMount()
vi. componentWillReceiveProps()
vii. shouldComponentUpdate()
viii. componentWillUpdate()
ix. componentDidUpdate()
x. componentWillUnmount()
xi. click handlers or event handlers
like onClickSubmit() or onChangeDescription()
xii. getter methods for render
like getSelectReason() or getFooterContent()
xiii. optional render methods
like renderNavigation() or renderProfilePicture()
xiv. render()
const PAGES = {
home: HomePage,
about: AboutPage,
services: ServicesPage,
contact: ContactPage,
};
// The keys of the PAGES object can be used in the prop types to catch
dev-time errors.
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired,
};
Let's say the initial count value is zero. After three consecutive
increment operations, the value is going to be incremented only by
one.
(OR)
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
i. onPointerDown
ii. onPointerMove
iii. onPointerUp
iv. onPointerCancel
v. onGotPointerCapture
vi. onLostPointerCapture
vii. onPointerEnter
viii. onPointerLeave
ix. onPointerOver
x. onPointerOut
You can define component class which name starts with lowercase
letter, but when it's imported it should have capital letter. Here
lowercase is fine:
While when imported in another file it should start with capital letter:
The component names should start with an uppercase letter but there
are few exceptions to this convention. The lowercase tag names with a
dot (property accessors) are still considered as valid component
names. For example, the below tag can be compiled to a valid
component,
render() {
return (
<obj.component/> // `React.createElement(obj.component)`
)
}
87. Are custom DOM attributes supported in
React v16?
Yes. In the past, React used to ignore unknown DOM attributes. If you
wrote JSX with an attribute that React doesn't recognize, React would
just skip it.
<div />
Using React.createClass():
const MyComponent = React.createClass({
getInitialState() {
return {
/* initial state */
};
},
});
Note: React.createClass() is deprecated and removed in React v16.
Use plain JavaScript classes instead.
Using super():
class MyComponent extends React.Component {
constructor(props) {
super();
console.log(this.props); // undefined
}
}
This is because JSX tags are transpiled into function calls, and you
can't use statements inside expressions. This may change thanks
to do expressions which are stage 1 proposal.
But you can put any JS expression inside curly braces as the entire
attribute value. So the below expression works:
Instead you need to move curly braces outside (don't forget to include
spaces between class names):
<button
style={{ ...styles.panel.button, ...styles.panel.submitButton }}>
{"Submit"}
</button>
If you're using React Native then you can use the array notation:
useEffect(() => {
function handleResize() {
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return (
<span>
{dimensions.width} x {dimensions.height}
</span>
);
}
render() {
return false
}
render() {
return true
}
render() {
return null
}
render() {
return []
}
render() {
return ""
}
render() {
return <React.Fragment></React.Fragment>
}
render() {
return <></>
}
render() {
return undefined
}
render() {
return (
<div>
<input defaultValue={"Won't focus"} />
<input
ref={(input) => (this.nameInput = input)}
defaultValue={"Will focus"}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
useEffect(() => {
inputElRef.current.focus();
}, []);
return (
<div>
<input defaultValue={"Won't focus"} />
<input ref={inputElRef} defaultValue={"Will focus"} />
</div>
);
};
ReactDOM.render(
<div>{`React version: ${REACT_VERSION}`}</div>,
document.getElementById("app")
);
componentWillUnmount() {
clearInterval(this.interval)
}
<div
style={{
transform: "rotate(90deg)",
WebkitTransform: "rotate(90deg)", // note the capital 'W' here
msTransform: "rotate(90deg)", // 'ms' is the only lowercase vendor
prefix
}}
/>
With the export specifier, the MyProfile is going to be the member and
exported to this module and the same can be imported without
mentioning the name in other components.
this.inputElement.click();
common/
├─ Avatar.js
├─ Avatar.css
├─ APIUtils.js
└─ APIUtils.test.js
feed/
├─ index.js
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
└─ FeedAPI.js
profile/
├─ index.js
├─ Profile.js
├─ ProfileHeader.js
├─ ProfileHeader.css
└─ ProfileAPI.js
api/
├─ APIUtils.js
├─ APIUtils.test.js
├─ ProfileAPI.js
└─ UserAPI.js
components/
├─ Avatar.js
├─ Avatar.css
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
├─ Profile.js
├─ ProfileHeader.js
└─ ProfileHeader.css
For example, the employees list fetched from API and set local state:
componentDidMount() {
fetch("https://api.example.com/items")
.then((res) => res.json())
.then(
(result) => {
this.setState({
employees: result.employees,
});
},
(error) => {
this.setState({ error });
}
);
}
render() {
const { error, employees } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else {
return (
<ul>
{employees.map((employee) => (
<li key={employee.name}>
{employee.name}-{employee.experience}
</li>
))}
</ul>
);
}
}
}
Libraries such as React Router and DownShift are using this pattern.
React Router
i. <BrowserRouter>
ii. <HashRouter>
iii. <MemoryRouter>
The above components will create browser, hash, and memory history
instances. React Router v4 makes the properties and methods of
the history instance associated with your router available through the
context in the router object.
i. push()
ii. replace()
135. Why you get "Router may have only one child
element" warning?
You have to wrap your Route's in a <Switch> block because <Switch> is
unique in that it renders a route exclusively.
At first you need to add Switch to your imports:
import { Switch, Router, Route } from "react-router";
xii. You can also use push method of history object similar to built-in
history object:
xiii. // some-other-file.js
xiv. import history from "./history";
xv.
history.push("/go-here");
React Internationalization
ii. <FormattedMessage
iii. id={"account"}
iv. defaultMessage={"The amount is less than minimum balance."}
/>
v. Using an API:
MyComponent.propTypes = {
intl: intlShape.isRequired,
};
MyComponent.propTypes = {
intl: intlShape.isRequired,
};
function MyComponent() {
return (
<div>
<span className={"heading"}>{"Title"}</span>
<span className={"description"}>{"Description"}</span>
</div>
);
}
// in your test
const renderer = new ShallowRenderer();
renderer.render(<MyComponent />);
expect(result.type).toBe("div");
expect(result.props.children).toEqual([
<span className={"heading"}>{"Title"}</span>,
<span className={"description"}>{"Description"}</span>,
]);
console.log(testRenderer.toJSON());
// {
// type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ]
// }
Finally, run yarn test or npm test and Jest will print a result:
$ yarn test
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (2ms)
React Redux
const mapDispatchToProps = {
onTodoClick,
};
render() {
return this.props.isLoaded ? (
<div>{"Loaded"}</div>
) : (
<div>{"Not Loaded"}</div>
);
}
}
state = undefined;
}
o Without decorator:
The above examples are almost similar except the usage of decorator.
The decorator syntax isn't built into any JavaScript runtimes yet, and is
still experimental and subject to change. You can use babel for the
decorators support.
function setAccount(data) {
return { type: "SET_Account", data: data };
}
ii. In reducers:
You can use this object to decide what to return from those functions.
This structure works well for small and medium size apps.
175. What is redux-saga?
redux-saga is a library that aims to make side effects (asynchronous
things like data fetching and impure things like accessing the browser
cache) in React/Redux applications easier and better.
It is available in NPM:
Let's take example of how these effects work for fetching particular
user data.
function* fetchUserSaga(action) {
// `call` function accepts rest arguments, which will be passed to
`api.fetchUser` function.
// Instructing middleware to call promise, it resolved value will be
assigned to `userData` variable
const userData = yield call(api.fetchUser, action.userId);
const initialState = {
todos: [{ id: 123, name: "example", completed: false }],
};
For example, let's take an action which represents adding a new todo
item:
{
type: ADD_TODO,
text: 'Add todo item'
}
React Native
Reselect keeps a copy of the last inputs/outputs of the last call, and
recomputes the result only if one of the inputs changes. If the the
same inputs are provided twice in a row, Reselect returns the cached
output. It's memoization and cache are fully customizable.
i. Install font-awesome:
$ npm install --save font-awesome
i. Chrome extension
ii. Firefox extension
iii. Standalone app (Safari, React Native, etc)
Note: The above list of advantages are purely opinionated and it vary based
on the professional experience. But they are helpful as base parameters.
200. What is the difference between React and
Angular?
Let's see the difference between React and Angular in a table format.
React Angular
React is a library and has only the Angular is a framework and has complete
View layer MVC functionality
React handles rendering on the AngularJS renders only on the client side but
server side Angular 2 and above renders on the server side
React uses JSX that looks like Angular follows the template approach for
HTML in JS which can be HTML, which makes code shorter and easy to
confusing understand
Note: The above list of differences are purely opinionated and it vary based
on the professional experience. But they are helpful as base parameters.
These two variables, Title and Wrapper, are now components that you
can render just like any other react component.
<Wrapper>
<Title>{"Lets start first styled component!"}</Title>
</Wrapper>
# or
yarn create react-app my-app --typescript
my-app/
├─ .gitignore
├─ images.d.ts
├─ node_modules/
├─ public/
├─ src/
│ └─ ...
├─ package.json
├─ tsconfig.json
├─ tsconfig.prod.json
├─ tsconfig.test.json
└─ tslint.json
Miscellaneous
let exampleState = {
shop: {
taxPercent: 8,
items: [
{ name: "apple", value: 1.2 },
{ name: "orange", value: 0.95 },
],
},
};
console.log(subtotalSelector(exampleState)); // 2.15
console.log(taxSelector(exampleState)); // 0.172
console.log(totalSelector(exampleState)); // { total: 2.322 }
Component.propTypes = {...}
Component.someMethod = function(){....}
If your initialValues prop gets updated, your form will update too.
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={(input) => (this.input = input)} /> //
Access DOM input in handle submit
<button type="submit">Submit</button>
</form>
);
}
}
But our expectation is for the ref callback to get called once, when the
component mounts. One quick fix is to use the ES7 class property
syntax to define the function
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={this.setSearchInput} /> // Access DOM
input
in handle submit
<button type="submit">Submit</button>
</form>
);
}
}
function ppHOC(WrappedComponent) {
return class PP extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
};
}
Inheritance Inversion
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
return super.render();
}
};
}
React.render(
<User age={30} department={"IT"} />,
document.getElementById("container")
);
Below are the thumb rules to determine what kind of data should be
put into Redux
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
You can also merge this array of items in another array component.
Strings and Numbers: You can also return string and number type
from the render method.
render() {
return 'Welcome to ReactJS questions';
}
// Number
render() {
return 2018;
}
handleIncrement = () => {
this.setState((prevState) => ({
value: prevState.value + 1,
}));
};
handleDecrement = () => {
this.setState((prevState) => ({
value: prevState.value - 1,
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.handleIncrement}>+</button>
<button onClick={this.handleDecrement}>-</button>
</div>
);
}
}
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</>
);
}
For example, the linter enforce proper naming convention for hooks. If
you rename your custom hooks which as prefix "use" to something
else then linter won't allow you to call built-in hooks such as useState,
useEffect etc inside of your custom hook anymore.
Flux Redux
There are multiple stores exist There is only one store exist
All the stores are disconnected and flat Single store with hierarchical reducers
componentDidCatch(error, info);
If you need to catch an error inside an event handler, use the regular
JavaScript try / catch statement:
handleClick() {
try {
// Do something that could throw
} catch (error) {
this.setState({ error });
}
}
render() {
if (this.state.error) {
return <h1>Caught an error.</h1>;
}
return <button onClick={this.handleClick}>Click Me</button>;
}
}
For example, the try catch block used for below imperative code
try {
showButton();
} catch (error) {
// ...
}
Whereas error boundaries wrap declarative code as below,
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
For example, let us create color default prop for the button component,
function MyButton {
// ...
}
MyButton.defaultProps = {
color: "red",
};
If props.color is not provided then it will set the default value to 'red'.
i.e, Whenever you try to access the color prop it uses the default value
render() {
return <MyButton /> ; // props.color will contain red value
}
static getDerivedStateFromError(error)
Let us take error boundary use case with the above lifecycle method
for demonstration purpose,
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
i. static getDerivedStateFromProps()
ii. shouldComponentUpdate()
iii. render()
iv. getSnapshotBeforeUpdate()
v. componentDidUpdate()
i. static getDerivedStateFromError()
ii. componentDidCatch()
function withSubscription(WrappedComponent) {
class WithSubscription extends React.Component {
/* ... */
}
WithSubscription.displayName = `WithSubscription(${getDisplayName(
WrappedComponent
)})`;
return WithSubscription;
}
function getDisplayName(WrappedComponent) {
return (
WrappedComponent.displayName || WrappedComponent.name ||
"Component"
);
}
248. What is the browser support for react
applications?
React supports all popular browsers, including Internet Explorer 9 and
above, although some polyfills are required for older browsers such as
IE 9 and IE 10. If you use es5-shim and es5-sham polyfill then it
even support old browsers that doesn't support ES5 methods.
ReactDOM.unmountComponentAtNode(container);
For example, in the below code snippets, it will make moduleA.js and
all its unique dependencies as a separate chunk that only loads after
the user clicks the 'Load' button. moduleA.js
export { moduleA };
App.js
render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
}
}
function Glossary(props) {
return (
<dl>
{props.items.map((item) => (
// Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
Note: key is the only attribute that can be passed to Fragment. In the
future, there might be a support for additional attributes, such as
event handlers.
ii. render() {
iii. // A new version of EnhancedComponent is created on every
render
iv. // EnhancedComponent1 !== EnhancedComponent2
v. const EnhancedComponent = enhance(MyComponent);
vi. // That causes the entire subtree to unmount/remount each time!
vii. return <EnhancedComponent />;
}
viii. Static methods must be copied over: When you apply a HOC
to a component the new component does not have any of the
static methods of the original component
function enhance(WrappedComponent) {
class Enhance extends React.Component {
/*...*/
}
// Must know exactly which method(s) to copy :(
Enhance.staticMethod = WrappedComponent.staticMethod;
return Enhance;
}
xvii. Refs aren’t passed through: For HOCs you need to pass
through all props to the wrapped component but this does not
work for refs. This is because ref is not really a prop similar to
key. In this case you need to use the React.forwardRef API
For example, If you don't name the render function or not using
displayName property then it will appear as ”ForwardRef” in the
DevTools,
function logProps(Component) {
class LogProps extends React.Component {
// ...
}
return React.forwardRef(forwardRef);
}
i. Server-rendered by default
ii. Automatic code splitting for faster page loads
iii. Simple client-side routing (page based)
iv. Webpack-based dev environment which supports (HMR)
v. Able to implement with Express or any other Node.js HTTP server
vi. Customizable with your own Babel and Webpack configurations
<button onClick="{this.handleClick}"></button>
For example, lets take a ticking clock example, where it updates the
time by calling render method multiple times,
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById("root"));
}
setInterval(tick, 1000);
For example, let us take a facebook user with posts and comments
details as state variables,
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
Now you can update them independently with separate setState() calls
as below,
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
function Greeting(props) {
if (!props.loggedIn) {
return null;
}
render() {
return (
<div>
//Prevent component render if it is not loggedIn
<Greeting loggedIn={this.state.loggedIn} />
<UserDetails name={this.state.name}>
</div>
);
}
i. The list and items are static– they are not computed and do not
change
ii. The items in the list have no ids
iii. The list is never reordered or filtered.
For example, the below Book component uses two arrays with different
arrays,
function Book(props) {
const index = (
<ul>
{props.pages.map((page) => (
<li key={page.id}>{page.title}</li>
))}
</ul>
);
const content = props.pages.map((page) => (
<div key={page.id}>
<h3>{page.title}</h3>
<p>{page.content}</p>
<p>{page.pageNumber}</p>
</div>
));
return (
<div>
{index}
<hr />
{content}
</div>
);
}
For example, let us use Vaadin date picker web component as below,
import React, { Component } from "react";
import "./App.css";
import "@vaadin/vaadin-date-picker";
class App extends Component {
render() {
return (
<div className="App">
<vaadin-date-picker label="When were you born?"></vaadin-date-
picker>
</div>
);
}
}
export default App;
i. Normal Import
import("./math").then((math) => {
console.log(math.add(10, 20));
});
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
In the above code, the code splitting will happen at each route level.
ii. Static field You can use a static class field to initialize your
contextType using public class field syntax.
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
For example, the code below will re-render all consumers every time
the Provider re-renders because a new object is always created for
value.
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log("old props:", prevProps);
console.log("new props:", this.props);
}
render() {
const { forwardedRef, ...rest } = this.props;
Let's use this HOC to log all props that get passed to our “fancy
button” component,
// ...
}
export default logProps(FancyButton);
Note: If you use createReactClass then auto binding is available for all
methods. i.e, You don't need to use .bind(this) with in constructor for
event handlers.
ReactDOM.render(
<Greeting message="World" />,
document.getElementById("root")
);
You can write the same code without JSX as below,
ReactDOM.render(
React.createElement(Greeting, { message: "World" }, null),
document.getElementById("root")
);
vii. <ul>
viii. <li>first</li>
ix. <li>second</li>
x. </ul>
xi.
xii. <ul>
xiii. <li>first</li>
xiv. <li>second</li>
xv. <li>third</li>
</ul>
<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
289. When do you need to use refs?
There are few use cases to go for refs,
<Mouse
children={(mouse) => (
<p>
The mouse position is {mouse.x}, {mouse.y}
</p>
)}
/>
<Mouse>
{(mouse) => (
<p>
The mouse position is {mouse.x}, {mouse.y}
</p>
)}
</Mouse>
Mouse.propTypes = {
children: PropTypes.func.isRequired,
};
291. What are the problems of using render props
with pure components?
If you create a function inside a render method, it negates the purpose
of pure component. Because the shallow prop comparison will always
return false for new props, and each render in this case will generate a
new value for the render prop. You can solve this issue by defining the
render function as instance method.
function withMouse(Component) {
return class extends React.Component {
render() {
return (
<Mouse
render={(mouse) => <Component {...this.props}
mouse={mouse} />}
/>
);
}
};
}
This way render props gives the flexibility of using either pattern.
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
User Name:
<input
defaultValue="John"
type="text"
ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
The same applies for select and textArea inputs. But you need to
use defaultChecked for checkbox and radio inputs.
297. What is your favorite React stack?
Even though the tech stack varies from developer to developer, the
most popular stack is used in react boilerplate project code. It mainly
uses Redux and redux-saga for state management and asynchronous
side-effects, react-router for routing purpose, styled-components for
styling react components, axios for invoking REST api, and other
supported stack such as webpack, reselect, ESNext, Babel. You can
clone the project https://github.com/react-boilerplate/react-
boilerplate and start working on any new react project.
You can update HTML directly. You Can’t directly update HTML
Creates a new DOM if element updates It updates the JSX if element update
iii. React Bootstrap Package: In this case, you can add Bootstrap to
our React app is by using a package that has rebuilt Bootstrap
components to work particularly as React components. Below
packages are popular in this category,
a. react-bootstrap
b. reactstrap
i. Facebook
ii. Uber
iii. Instagram
iv. WhatsApp
v. Khan Academy
vi. Airbnb
vii. Dropbox
viii. Flipboard
ix. Netflix
x. PayPal
function App() {
const [data, setData] = React.useState({ hits: [] });
React.useEffect(() => {
fetch("http://hn.algolia.com/api/v1/search?query=react")
.then(response => response.json())
.then(data => setData(data))
}, []);
return (
<ul>
{data.hits.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
i. React DOM
ii. React DOM Server
iii. React Test Renderer
iv. React Shallow Renderer
Programmin
It is mainly written in ES6 It is written in JavaScript(ES5)
g
There is only one large store There is more than one store for
Data Store
exist for data storage storage
How it stores Uses JS Object to store Uses observable to store the data
ii. // in es 5
iii. var someData = this.props.someData;
iv. var dispatch = this.props.dispatch;
v.
vi. // in es6
const { someData, dispatch } = this.props;
viii. // in es 5
ix. <SomeComponent someData={this.props.someData}
dispatch={this.props.dispatch} />
x.
xi. // in es6
<SomeComponent {...this.props} />
xiii. // es 5
xiv. var users = usersList.map(function (user) {
xv. return <li>{user.name}</li>;
xvi. });
xvii. // es 6
const users = usersList.map((user) => <li>{user.name}</li>);
Remember that the future versions will throw an error for javascript
URLs.
if (user.likes()) {
if (hasBlue()) {
removeBlue();
addGrey();
} else {
removeGrey();
addBlue();
}
}
if (this.state.liked) {
return <blueLike />;
} else {
return <greyLike />;
}
App.js
But while using Context API, to access context in App.js, wrap the
AuthState in index.js so that App.js can access the auth context. Now
whenever the page reloads, no matter what route you are on, the user
will be authenticated as loadUser action will be triggered on each re-
render.
index.js
ReactDOM.render(
<React.StrictMode>
<AuthState>
<App />
</AuthState>
</React.StrictMode>,
document.getElementById("root")
);
App.js
const authContext = useContext(AuthContext);
useEffect(() => {
loadUser();
}, []);
loadUser
if (!token) {
dispatch({
type: ERROR,
});
}
setAuthToken(token);
try {
const res = await axios("/api/auth");
dispatch({
type: USER_LOADED,
payload: res.data.data,
});
} catch (err) {
console.error(err);
}
};
Let's take an example to look at the main differences between the old
and the new transform,
Old Transform:
function App() {
return <h1>Good morning!!</h1>;
}
Now JSX transform convert the above code into regular JavaScript as
below,
function App() {
return React.createElement("h1", null, "Good morning!!");
}
New Transform:
function App() {
return <h1>Good morning!!</h1>;
}
function App() {
return _jsx("h1", { children: "Good morning!!" });
}
This can cause unknown issues in the UI as the value of the state
variable got updated without telling React to check what all
components were being affected from this update and it can cause UI
bugs.
Ex:
componentDidMount() {
let { loading } = this.state;
loading = (() => true)(); // Trying to perform an operation and
directly saving in a state variable
}
How to prevent it: Make sure your state variables are immutable by
either enforcing immutability by using plugins like Immutable.js,
always using setState to make updates, and returning new instances in
reducers when sending updated state values.
Wrapper component can also accept its own props and pass them
down to the wrapped component, for example, we can create a
wrapper component that will add a title to the message component:
1. Syntax:
The classs components uses ES6 classes to create the components. It
uses render function to display the HTML content in the webpage.
Functional component has been improved over the years with some
added features like Hooks. Here is a syntax for functional component.
function App(){
return <div className="App">
<h1>Hello, I'm a function component</h1>
</div>
}
2. State:
State contains information or data about a component which may
change over time.
In class component, you can update the state when a user interacts
with it or server updates the data using the setState() method. The
initial state is going to be assigned in the Constructor( ) method using
the the this.state object and it is possible to different data types in
the this.state object such as string, boolean, numbers, etc. A simple
example showing how we use the setState() and constructor()
class App extends Component {
constructor() {
super();
this.state = {
message: "This is a class component",
};
}
updateMessage() {
this.setState({t
message: "Updating the class component",
});
}
render() {
return (
<>
<h1>{this.state.message}</h1>
<button
onClick={() => {
this.updateMessage();
}}>
Click!!
</button>
</>
);
}
}
function App() {
const [message, setMessage] = useState("This is a functional
component");
const updateMessage = () => {
setMessage("Updating the functional component");
};
return (
<div className="App">
<h1>{message} </h1>
<button onClick={updateMessage}>Click me!!</button>
</div>
);
}
4. Props:
Props are referred to as "properties". The props are passed into react
component just like arguments passed to a function. In otherwords,
they are similar to HTML attributes.
function Child(props) {
return <h1>This is a child component and the component name
is{props.name}</h1>;
}
function Parent() {
return (
<div className="Parent">
<Child name="First child component" />
<Child name="Second child component" />
</div>
);
}
```jsx harmony
import React from "react";
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Header />
</div>
);
}
```
In the example above, the _strict mode_ checks apply to `<ComponentOne>` and
`<ComponentTwo>` components only. i.e., Part of the application only.
**[ ](#table-of-contents)**
If you want to disable this behavior then you can remove strict mode.
ReactDOM.render(
{App},
document.getElementById('root')
);
Disclaimer
The questions provided in this repository are the summary of frequently
asked questions across numerous companies. We cannot guarantee that
these questions will actually be asked during your interview process, nor
should you focus on memorizing all of them. The primary purpose is for you
to get a sense of what some companies might ask — do not get discouraged
if you don't know the answer to all of them — that is ok!
Source: https://github.com/sudheerj/reactjs-interview-questions