Important React Interview Questions
Q. Create a component, that displays data from https://reqres.in/api/users?
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get("https://reqres.in/api/users?page=1").then((response) => {
setUsers(response.data.data);
});
}, []);
return (
<>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.first_name} {user.last_name}
</li>
))}
</ul>
</>
);
}
Q. What is Destructuring in React?
Destructuring is a convenient way of accessing multiple properties stored in objects and arrays. It was introduced to JavaScript by ES6 and has provided developers with an increased amount of utility when accessing data properties in Objects or Arrays. When used, destructuring does not modify an object or array but rather copies the desired items from those data structures into variables. These new variables can be accessed later on in a React component. Example:
/**
* Destructuring in React
*/
import React from "react";
export default function App() {
// Destructuring
const [counter, setcounter] = React.useState(0);
return (
<>
<button onClick={() => setcounter(counter + 1)}> Increment </button>
<button onClick={() => setcounter(counter > 0 ? counter - 1 : 0)}>
Decrement
</button>
<h2>Result: {counter}</h2>
</>
);
}
## Q. How to add custom DOM attributes in JSX?
Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a render function, like so:
**Example:**
```js
// 1. Custom DOM Attribute
render() {
return (
);
}
// 2. Data Attribute ( starts with "data-" )
render() {
return (
);
}
// 3. ARIA Attribute ( starts with "aria-" )
render() {
return (
);
}
```
## Q. How to use InnerHtml in React?
The **innerHTML** is risky because it is easy to expose users to a cross-site scripting (XSS) attack. React provides **dangerouslySetInnerHTML** as a replacement for innerHTML. It allows to set HTML directly from React by using `dangerouslySetInnerHTML` and passing an object with a `__html` key that holds HTML.
**Example:**
```js
function App() {
return (
);
}
```
## Q. What are React components?
Components are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e. properties(`props`) and returns a React element that describes how a section of the UI (User Interface) should appear.
A React component can be either **stateful** or **stateless**. A stateful component is a component that holds some state. Stateless components, by contrast, have no state.
**1. Stateless Component:**
```js
import React from 'react'
const ExampleComponent = () => {
return (Stateless Component
) } export default class App extends React.Component { render() { return (` element.
**2. Stateful Component:**
```js
import React from 'react'
class ExampleComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
heading: "Stateful Component"
}
}
render() {
return (
)
}
}
export default class App extends React.Component {
render() {
const welcomeMsg = "Welcome to React!"
return (
)
}
}
```
The above example shows a stateful component named ExampleComponent which is inserted in the ` ` component. The `ExampleComponent` contains a `` and the `` element wrapped in a ``. The `` displays data using props while the `` takes its data from the internal state of the ExampleComponent.
## Q. What is the difference between Component and Container in React?
The **presentational** components are concerned with the look, **container** components are concerned with making things work.
For example, this is a presentational component. It gets data from its props, and just focuses on showing an element
```js
/**
* Presentational Component
*
**/
const Users = props => (
{props.users.map(user => (
- {user}
))}
)
```
On the other hand this is a container component. It manages and stores its own data, and uses the presentational component to display it.
```js
/**
* Container Component
*
**/
class UsersContainer extends React.Component {
constructor() {
this.state = {
users: []
}
}
componentDidMount() {
axios.get('/users').then(users =>
this.setState({ users: users }))
)
}
render() {
return
}
}
```
## Q. How would you prevent a component from rendering?
React **shouldComponentUpdate()** is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. This method only used when a component will stay static or pure.
The React `shouldComponentUpdate()` method return `true` if it needs to re-render or `false` to avoid being re-render.
**Syntax:**
```js
shouldComponentUpdate(nextProps, nextState){ }
```
**Example:**
```js
/**
* Prevent a component from rendering
*/
export default class App extends React.Component {
constructor() {
super();
this.state = {
countOfClicks: 0
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
countOfClicks: this.state.countOfClicks + 1
});
}
shouldComponentUpdate(nextProps, nextState) {
console.log("this.state.countOfClicks", this.state.countOfClicks);
console.log("nextState.countOfClicks", nextState.countOfClicks);
return true;
}
render() {
return (
shouldComponentUpdate Example
Count of clicks: {this.state.countOfClicks}
);
}
}
```
## Q. What is Compound Components in React?
A compound component is a type of component that manages the internal state of a feature while delegating control of the rendering to the place of implementation opposed to the point of declaration. They provide a way to shield feature specific logic from the rest of the app providing a clean and expressive API for consuming the component.
Internally they are built to operate on a set of data that is passed in through children instead of props. Behind the scenes they make use of React\'s lower level API such as `React.children.map()`, and `React.cloneElement()`. Using these methods, the component is able to express itself in such a way that promotes patterns of composition and extensibility.
**Example:**
```js
function App() {
return (
)
}
```
In this example, the `
);
}
```
**Example:**
```js
/**
* React Lazy Loading Routes
*/
import React, { Suspense, lazy } from "react";
import { Switch, BrowserRouter as Router, Route, Link } from "react-router-dom";
const Home = lazy(() => import("./Home"));
const ContactUs = lazy(() => import("./ContactUs"));
const HelpPage = lazy(() => import("./Help"));
export default function App() {
return (
- Home
- ContactUs
- HelpPage
Loading...
}>
);
}
```
## Q. What is props in React?
**Props** is a special keyword in React, which stands for properties and is being used for passing data from one component to another. However, callback functions can also be passed, which can be executed inside the child to initiate an update.
Props are **immutable** so we cannot modify the props from inside the component. These attributes are available in the class component as **this.props** and can be used to render dynamic data in our render method.
**Example:**
```js
function Welcome(props) {
return Hello, {props.name}
;
}
const element = ;
```
## Q. What are default props?
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed.
The `defaultProps` can be defined as a property on the component class itself to set the default props for the class. `defaultProps` is used for **undefined** props, not for **null** props.
```js
/**
* Default Props
*/
class MessageComponent extends React.Component {
render() {
return (
Hello, {this.props.value}.
)
}
}
// Default Props
MessageComponent.defaultProps = {
value: 'World'
}
ReactDOM.render(
,
document.getElementById('default')
)
ReactDOM.render(
,
document.getElementById('custom')
)
```
**
## Q. How to apply validation on Props in React?
Props are an important mechanism for passing the **read-only** attributes to React components. React provides a way to validate the props using `PropTypes`. This is extremely useful to ensure that the components are used correctly.
**Example:**
```js
/**
* Props Validation
*/
import React from "react";
import PropTypes from "prop-types";
export default class App extends React.Component {
render() {
return (
<>
Boolean: {this.props.propBool ? "True" : "False"}
Array: {this.props.propArray}
Number: {this.props.propNumber}
String: {this.props.propString}
>
);
}
}
App.defaultProps = {
propBool: true,
propArray: [10, 20, 30],
propNumber: 100,
propString: "Hello React!"
};
App.propTypes = {
propBool: PropTypes.bool.isRequired,
propArray: PropTypes.array.isRequired,
propNumber: PropTypes.number,
propString: PropTypes.string
};
```
## Q. What are render props?
The term **render props** refers to a technique for sharing code between React components using a prop whose value is a function.
In simple words, render props are simply props of a component where you can pass functions. These functions need to return elements, which will be used in rendering the components.
**Example:**
```js
/**
* Render Props
*/
import React from "react";
import Wrapper from "./Wrapper";
class App extends React.Component {
render() {
return (
(
Render Props Counter
{count}
)}
/>
);
}
}
```
```js
/**
* Wrapper Component
*/
class Wrapper extends React.Component {
state = {
count: 0
};
// Increase count
increment = () => {
const { count } = this.state;
return this.setState({ count: count + 1 });
};
render() {
const { count } = this.state;
return (
{this.props.render({ increment: this.increment, count: count })}
);
}
}
```
**
## Q. How do you create Higher Order Component using render props?
It is possible to implement most higher-order components (HOC) using a regular component with a render prop. This way render props gives the flexibility of using either pattern.
**Example:**
```js
function withMouse(Component) {
return class extends React.Component {
render() {
return (
(
)}/>
);
}
}
}
```
## Q. What is children props?
The `{this.props.children}` is a special prop, automatically passed to every component, that can be used to render the content included between the opening and closing tags when invoking a component.
**Example:**
```js
/**
* React Children Props
*/
class MyComponent extends React.Component {
render() {
return (
React Children Props Example
{this.props.children}
);
}
}
class OtherComponent extends React.Component {
render() {
return Other Component Props;
}
}
ReactDOM.render(
React DOM Props
{/* Children Props*/}
,
document.getElementById("root")
);
```
**
## Q. Why we need to be careful when spreading props on DOM elements?
When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice.
**Problem:** This will try to add the unknown HTML attribute `flag` to the DOM element.
```js
const Sample = () => ( );
const Spread = (props) => (Test);
```
**Solution:** By creating props specifically for DOM attribute, we can safely spread.
```js
const Sample = () => ( );
const Spread = (props) => (Test);
```
Or alternatively we can use prop destructuring with `...rest`:
```js
const Sample = () => ( );
const Spread = ({ flag, ...domProps }) => (Test);
```
**Note:**
*In scenarios where you use a PureComponent, when an update happens it re-renders the component even if domProps did not change. This is because PureComponent only shallowly compares the objects.*
## Q. When should I be using React.cloneElement vs this.props.children?
The `React.cloneElement` only works if your child is a single React element.
**Example:**
```js
{React.cloneElement(this.props.children, {
key: this.props.location.pathname
})}
```
For almost everything `{this.props.children}` is used. Cloning is useful in some more advanced scenarios, where a parent sends in an element and the child component needs to change some props on that element or add things like `ref` for accessing the actual DOM element.
**Example:**
```js
class Users extends React.Component {
render() {
return (
Users
{this.props.children}
)
}
}
```
## Q. How to pass JSON Objects from Child to Parent Component?
**Example:** Passing JSON Objects from Child to Parent Component using callback function
```js
// Parent Component
export default class App extends React.Component {
constructor() {
super();
this.state = {
message: ""
};
this.onSubmitMessage = this.onSubmitMessage.bind(this);
}
onSubmitMessage(message) {
this.setState({ message: message });
}
render() {
const { message } = this.state;
return (
);
}
}
```
```js
// Child Component
export default class Child extends React.Component {
constructor() {
super();
this.state = {
greetingMessag: ""
};
this.onMessageChange = this.onMessageChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onMessageChange(event) {
let message = event.target.value;
this.setState({ greetingMessag: message });
}
// pass message to parent component using callback
onSubmit() {
this.props.onSubmitMessage(this.state.greetingMessag);
}
render() {
return (
);
}
}
```
## Q. What is the use of this props?
It is called spread operator (ES6 feature) and its aim is to make the passing of props easier.
**Example:**
```js
Content Here
```
It is equal to Class Component
```js
const person = {
name: "Alex",
age: 26,
country: "India"
}
class SpreadExample extends React.Component {
render() {
const {name, age, country} = {...this.props}
return (
Person Information:
- name={name}
- age={age}
- country={country}
)
}
}
ReactDOM.render(
, mountNode
)
```
## Q. What is the second argument that can optionally be passed to setState() and what is its purpose?
A **callback function** which will be invoked when `setState()` has finished and the component is re-rendered. The setState() is asynchronous, which is why it takes in a second callback function. Typically it\'s best to use another lifecycle method rather than relying on this callback function, but it is good to know it exists.
**Example:**
```js
this.setState(
{ username: 'Lila' },
() => console.log('setState has finished and the component has re-rendered.')
)
```
The setState() will always lead to a re-render unless `shouldComponentUpdate()` returns **false**. To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like `componentDidUpdate()`.
## Q. How to delete an item from state array?
When using React, we should never mutate the state directly. If an object is changed, we should create a new copy. The better approach is to use `Array.prototype.filter()` method which creates a new array.
**Example:**
```js
onDeleteByIndex(index) {
this.setState({
users: this.state.users.filter((item, i) => i !== index)
});
}
```
**
## Q. How can you re-render a component without using setState() function?
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
However, there may be cases where the render() method depends on some other data. After the initial mounting of components, a re-render will occur.
**Using forceUpdate():**
The following example generates a random number whenever it loads. Upon clicking the button, the `forceUpdate()` function is called which causes a new, random number to be rendered:
```js
/**
* forceUpdate()
*/
export default class App extends React.Component {
constructor(){
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};
forceUpdateHandler(){
this.forceUpdate();
};
render(){
return(
);
}
}
```
**
*Note: We should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in render().*
## Q. Why we need to pass a function to setState()?
The reason behind for this is that `setState()` is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after `setState()` is called. That means we should not rely on the current state when calling `setState()`.
The solution is to **pass a function to setState()**, with the previous state as an argument. By doing this we can avoid issues with the user getting the old state value on access due to the asynchronous nature of `setState()`.
**Problem:**
```js
// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3
```
**
**Solution:**
```js
this.setState((prevState) => ({
count: prevState.count + 1
}));
this.setState((prevState) => ({
count: prevState.count + 1
}));
this.setState((prevState) => ({
count: prevState.count + 1
}));
// this.state.count === 3 as expected
```
**
## Q. How to update nested state properties in React.js?
We can pass the old nested object using the spread operator and then override the particular properties of the nested object.
**Example:**
```js
// Nested object
state = {
name: 'Vyasa Agarwal',
address: {
colony: 'Old Cross Rds, Mehdipatnam',
city: 'Patna',
state: 'Jharkhand'
}
};
handleUpdate = () => {
// Overriding the city property of address object
this.setState({ address: { ...this.state.address, city: "Ranchi" } })
}
```
**
## Q. How to set state with a dynamic key name?
If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with *computed property* names.
```js
inputChangeHandler : function (event) {
this.setState({ [event.target.id]: event.target.value });
// alternatively using template strings for strings
// this.setState({ [`key${event.target.id}`]: event.target.value });
}
```
**
## Q. How to listen state change in React.js?
The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.
```js
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
```
In functional component, listen state changes with useEffect hook like this
```js
export function MyComponent(props) {
const [myState, setMystate] = useState('initialState')
useEffect(() => {
console.log(myState, '- Has changed')
},[myState]) // <-- here put the parameter to listen
}
```
## Q. How to access child\'s state in React?
**Using Refs:**
In React we can access the child\'s state using `React.createRef()`. We will assign a Refs for the child component in the parent component, then using Refs we can access the child\'s state.
```js
// App.js
class App extends React.Component {
constructor(props) {
super(props);
this.ChildElement = React.createRef();
}
handleClick = () => {
const childelement = this.ChildElement.current;
childelement.getMsg("Message from Parent Component!");
};
render() {
return (
);
}
}
```
```js
// Child.js
class Child extends React.Component {
state = {
name: "Message from Child Component!"
};
getMsg = (msg) => {
this.setState({
name: msg
});
};
render() {
return {this.state.name}
;
}
}
```
**
## Q. How to change the state of a child component from its parent in React?
To change child component\'s state from parent component with React, we can pass props.
```js
/**
* Change Child state from its Parent
* @param {*} param0
*/
const Child = ({ open }) => {
return Child State: {open.toString()}
;
};
const Parent = () => {
const [isOpen, setIsOpen] = React.useState(false);
const toggleChild = () => {
setIsOpen((prevValue) => !prevValue);
};
return (
{/* Pass a callback to Child */}
);
};
export default Parent;
```
## Q. How to pass a parameter to event handlers in React?
**Example:**
```js
const message = "Hey there!";
export default class App extends React.Component {
displayMessage(message) {
alert(message);
}
render() {
return (
);
}
}
```
## Q. How do you pass an event handler to a component?
**Example:**
```js
import React, {useState} from "react";
import "./styles.css";
export default function App() {
return (
);
}
const Container = () => {
const [counter, setCounter] = useState(0);
const handleCustomClick = () => {
setCounter(counter + 1)
}
return (
Counter: {counter}
);
}
const CustomButton = ({onCustomClick}) => {
return (
);
}
```
## Q. How to bind methods or event handlers in JSX callbacks?
There are 3 possible ways to achieve this
**1. Event Handler in Render Method:**
We can bind the handler when it is called in the render method using `bind()` method.
```js
handleClick() {
// ...
}
```
**
**2. Event Handler using Arrow Function:**
In this approach we are binding the event handler implicitly. This approach is the best if you want to pass parameters to your event.
```js
handleClick() {
// ...
}
```
**
**3. Event Handler in Constructor:**
This has performance benefits as the events aren\'t binding every time the method is called, as opposed to the previous two approaches.
```js
constructor(props) {
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// ...
}
```
**
## Q. When should we use arrow functions with React?
**Arrows prevent `this` bugs**
Arrow functions don not redefine the value of `this` within their function body. This makes it a lot easier to predict their behavior when passed as callbacks, and prevents bugs caused by use of this within callbacks. Using inline arrow functions in function components is a good way to achieve some decoupling.
**Example:**
```js
import React from 'react'
import ReactDOM from 'react-dom'
class Button extends React.Component {
render() {
return (
)
}
handleClick = () => {
this.setState({ backgroundColor: 'red' })
}
}
ReactDOM.render(
,
document.getElementById('root')
)
```
1. When we use `this` it generates a new function on every render, which will obviously have a new reference.
2. If the component we pass this generated function to is extending `PureComponent()`, it will not be able to bail out on rerendering, even if the actual data has not changed.
## Q. How can I prevent a function from being called too quickly?
**1. Throttle:**
Throttling prevents a function from being called more than once in a given window of time.
**2. Debounce:**
Debouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called. This can be useful when you have to perform some expensive calculation in response to an event that might dispatch rapidly (eg scroll or keyboard events).
**Example:**
```js
/**
* Throttle and Debounce in React
*/
import * as React from "react";
import * as _ from "lodash";
export default class App extends React.Component {
state = { count: 0 };
handleCount() {
this.setState((state) => ({
count: state.count + 1
}));
}
// You will run count() only once after 100ms
handleDebounce = _.debounce(() => this.handleCount(), 100);
// You will run count() every 200ms
handleThrottle = _.throttle(() => this.handleCount(), 200);
render() {
return (
{this.state.count}
);
}
}
```
**3. RequestAnimationFrame Throttling:**
The **requestAnimationFrame** is a way of queuing a function to be executed in the browser at the optimal time for rendering performance. A function that is queued with requestAnimationFrame will fire in the next frame. The browser will work hard to ensure that there are 60 frames per second (60 fps). However, if the browser is unable to it will naturally limit the amount of frames in a second.
For example, a device might only be able to handle 30 fps and so you will only get 30 frames in that second. Using requestAnimationFrame for throttling is a useful technique in that it prevents you from doing more than 60 updates in a second. If you are doing 100 updates in a second this creates additional work for the browser that the user will not see anyway.
```js
/**
* RequestAnimationFrame Throttling
*/
import rafSchedule from "raf-schd";
import React from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
// Create a new function to schedule updates.
this.scheduleUpdate = rafSchedule((point) => this.props.onScroll(point));
}
handleScroll(e) {
// When we receive a scroll event, schedule an update.
// If we receive many updates within a frame, we'll only publish the latest value.
this.scheduleUpdate({ x: e.clientX, y: e.clientY });
}
componentWillUnmount() {
// Cancel any pending updates since we're unmounting.
this.scheduleUpdate.cancel();
}
render() {
return (
);
}
}
```
## Q. Explain synthetic event in React js?
Inside React event handlers, the event object is wrapped in a `SyntheticEvent` object. These objects are pooled, which means that the objects received at an event handler will be reused for other events to increase performance. This also means that accessing the event object\'s properties asynchronously will be impossible since the event\'s properties have been reset due to reuse.
The following piece of code will log null because event has been reused inside the SyntheticEvent pool:
```js
function handleClick(event) {
setTimeout(function () {
console.log(event.target.name)
}, 1000)
}
```
To avoid this we need to store the event\'s property:
```js
function handleClick(event) {
let name = event.target.name
setTimeout(function () {
console.log(name)
}, 1000)
}
```
**SyntheticEvent Object:**
```js
void preventDefault()
void stopPropagation()
boolean isPropagationStopped()
boolean isDefaultPrevented()
void persist()
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
DOMEventTarget target
number timeStamp
string type
```
## Q. What is Event Pooling in React?
The `SyntheticEvent` is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an `asynchronous` way.
**Example:**
```js
function onClick(event) {
console.log(event) // => nullified object.
console.log(event.type) // => "click"
const eventType = event.type // => "click"
setTimeout(function() {
console.log(event.type) // => null
console.log(eventType) // => "click"
}, 0)
// Won't work. this.state.clickEvent will only contain null values.
this.setState({clickEvent: event})
// You can still export event properties.
this.setState({eventType: event.type})
}
```
If we want to access the event properties in an asynchronous way, we should call `event.persist()` on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
## Q. How to trigger click event programmatically?
We can use `ref` prop to acquire a reference to the underlying `HTMLInputElement` object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the `HTMLElement.click` method.
**Example:**
```js
class MyComponent extends React.Component {
render() {
return (
this.inputElement = input} />
)
}
handleClick = (e) => {
this.inputElement.click()
}
}
```
*Note: The `ES6 arrow function` provides the correct lexical scope for `this` in the callback.*
## Q. How to listen for click events that are outside of a component?
**Example:**
```js
class OutsideAlerter extends Component {
// ...
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Set the wrapper ref
*/
setWrapperRef(node) {
this.wrapperRef = node;
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return {this.props.children};
}
}
OutsideAlerter.propTypes = {
children: PropTypes.element.isRequired
};
```
## Q. How to convert text to uppercase on user input entered?
```js
import React, { useState } from "react"
import ReactDOM from "react-dom"
const toInputUppercase = e => {
e.target.value = ("" + e.target.value).toUpperCase()
}
const App = () => {
const [name, setName] = useState("")
return (
setName(e.target.value)}
onInput={toInputUppercase} // apply on input which do you want to be capitalize
/>
)
}
ReactDOM.render( , document.getElementById("root"))
```
## Q. How to set a dynamic key for state?
**1. Dynamic Key:**
```js
onChange(e) {
const key = e.target.name
const value = e.target.value
this.setState({ [key]: value })
}
```
**2. Nested States:**
```js
handleSetState(cat, key, val) {
const category = {...this.state[cat]}
category[key] = val
this.setState({ [cat]: category })
}
```
## Q. Explain the Lists in React?
Using JSX we can show lists using JavaScript\'s built-in `Array.map()` method. The `.map()` method is often used to take one piece of data and convert it to another.
Keys are unique identifiers that must be attached to the top-level element inside a map. Keys are used by React to know how to update a list whether adding, updating, or deleting items. This is part of how React is so fast with large lists.
**Example:**
```js
/**
* React List
*/
export default class App extends Component {
state = {
lists: [
{ id: 0, context: "Success" },
{ id: 1, context: "Warning" },
{ id: 2, context: "Danger" }
]
};
render() {
return (
<>
React List
{this.state.lists.map((list) => (
- {list.context}
))}
>
);
}
}
```
## Q. How do you render Array, Strings and Numbers in React?
```js
/**
* Array Component
*/
const items = [
{ name: "AngularJS", description: "" },
{ name: "React", description: "" },
{ name: "Vue.js", description: "" }
];
const ArrayList = (props) => (
Render Array List
{items.map((item, index) => (
{item.name}
))}
);
/**
* String Component
*/
const StringList = (props) => (
Render String List
{["test", "render", "array", "list"]}
);
/**
* Number Component
*/
const numbers = [10, 20, 30];
const NumberList = (props) => (
Render Number List
{numbers.map((item, index) => (
{item}
))}
);
```
**
## Q. How to make a API calls in React?
Consuming REST APIs in a React Application can be done in various ways. Some popular are Axios, fetch etc.
**Example:**
```js
/**
* API call using fetch()
*/
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: []
};
}
componentDidMount() {
fetch("https://api.github.com/users")
.then((res) => res.json())
.then((result) => {
this.setState({ users: result });
});
}
render() {
const { users } = this.state;
return (
{users.map((user) => (
-
))}
);
}
}
```
## Q. How to display API data using Axios in React?
Axios is a promise based HTTP client for making HTTP requests from a browser to any web server.
**Example:**
```js
/**
* GET Request using Axios
*/
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function App() {
const [users, setUsers] = useState([]);
const fetchData = () => {
axios.get("https://jsonplaceholder.typicode.com/users").then((response) => {
setUsers(response.data);
});
};
useEffect(() => {
fetchData();
}, []);
return (
{users.length > 0 && (
{users.map((user) => (
- {user.name}
))}
)}
);
}
```
## Q. How does Axios Interceptors work in React?
Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.
Interceptors are methods which are triggered before or after the main method. There are two types of interceptors:
**1. Request Interceptor:**
It allows you to write or execute a piece of your code before the request gets sent. For example, an authentication token could be injected into all requests.
**Example:**
```js
// Request Handler
const requestHandler = (request) => {
const token = localStorageService.getAccessToken()
if (token) {
request.headers['Authorization'] = 'Bearer ' + token
}
return request
}
// Request Interceptor
axios.interceptors.request.use(
request => requestHandler(request)
)
```
**2. Response Interceptor:**
It allows you to write or execute a piece of your code before response reaches the calling end.
**Example:**
```js
// Response Handlers
const errorHandler = (error) => {
if (isHandlerEnabled(error.config)) {
// Handle errors
}
return Promise.reject({ ...error })
}
const successHandler = (response) => {
if (isHandlerEnabled(response.config)) {
// Handle responses
}
return response
}
// Response Interceptors
axios.interceptors.response.use(
response => successHandler(response),
error => errorHandler(error)
)
```
## Q. How to do caching in React?
In React, caching data can be achieved in multiple ways
* Local Storage
* Redux Store
* Keep data between mouting and unmounting
* useMemo()
**1. Memoizing Fetched Data:**
Memoization is a technique we would use to make sure that we don\'t hit the API if we have made some kind of request to fetch it at some initial phase. Storing the result of expensive fetch calls will save the users some load time, therefore, increasing overall performance.
**Example:**
```js
const cache = {}
const useFetch = (url) => {
const [status, setStatus] = useState('idle')
const [data, setData] = useState([])
useEffect(() => {
if (!url) return
const fetchData = async () => {
setStatus('fetching')
if (cache[url]) {
const data = cache[url]
setData(data)
setStatus('fetched')
} else {
const response = await fetch(url)
const data = await response.json()
cache[url] = data // set response in cache
setData(data)
setStatus('fetched')
}
}
fetchData()
}, [url])
return { status, data }
}
```
Here, we\'re mapping URLs to their data. So, if we make a request to fetch some existing data, we set the data from our local cache, else, we go ahead to make the request and set the result in the cache. This ensures we do not make an API call when we have the data available to us locally.
**2. Memoizing Data With useRef():**
With `useRef()`, we can set and retrieve mutable values at ease and its value persists throughout the component\'s lifecycle.
```js
const useFetch = (url) => {
const cache = useRef({})
const [status, setStatus] = useState('idle')
const [data, setData] = useState([])
useEffect(() => {
if (!url) return
const fetchData = async () => {
setStatus('fetching')
if (cache.current[url]) {
const data = cache.current[url]
setData(data)
setStatus('fetched')
} else {
const response = await fetch(url)
const data = await response.json()
cache.current[url] = data // set response in cache
setData(data)
setStatus('fetched')
}
}
fetchData()
}, [url])
return { status, data }
}
```
**3. Using localStorage():**
```js
const InitialState = {
someState: 'a'
}
class App extends Component {
constructor(props) {
super(props)
// Retrieve the last state
this.state = localStorage.getItem("appState") ? JSON.parse(localStorage.getItem("appState")) : InitialState
}
componentWillUnmount() {
// Remember state for the next mount
localStorage.setItem('appState', JSON.stringify(this.state))
}
render() {
...
}
}
export default App
```
**4. Keep data between Mouting and Unmounting:**
```js
import React, { Component } from 'react'
// Set initial state
let state = { counter: 5 }
class Counter extends Component {
constructor(props) {
super(props)
// Retrieve the last state
this.state = state
this.onClick = this.onClick.bind(this)
}
componentWillUnmount() {
// Remember state for the next mount
state = this.state
}
onClick(e) {
e.preventDefault()
this.setState(prev => ({ counter: prev.counter + 1 }))
}
render() {
return (
{ this.state.counter }
)
}
}
export default Counter
```
## Q. How to use async await in React?
**Example:**
```js
class App extends Component {
// ...
async componentDidMount() {
try {
const response = await fetch(`https://api.github.com/users`);
if (!response.ok) {
throw Error(response.statusText);
} else {
const json = await response.json();
this.setState({ data: json });
}
} catch (error) {
console.log(error);
}
}
render() {
return (
{this.state.data.map((el) => (
-
{el.login}
))}
);
}
}
```
## Q. How dynamically generate menu options for `
} />
` element wrapped in a ``. The `` displays data using props while the `` takes its data from the internal state of the ExampleComponent.
## Q. What is the difference between Component and Container in React?
The **presentational** components are concerned with the look, **container** components are concerned with making things work.
For example, this is a presentational component. It gets data from its props, and just focuses on showing an element
```js
/**
* Presentational Component
*
**/
const Users = props => (
{props.users.map(user => (
- {user}
))}
)
```
On the other hand this is a container component. It manages and stores its own data, and uses the presentational component to display it.
```js
/**
* Container Component
*
**/
class UsersContainer extends React.Component {
constructor() {
this.state = {
users: []
}
}
componentDidMount() {
axios.get('/users').then(users =>
this.setState({ users: users }))
)
}
render() {
return
}
}
```
## Q. How would you prevent a component from rendering?
React **shouldComponentUpdate()** is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. This method only used when a component will stay static or pure.
The React `shouldComponentUpdate()` method return `true` if it needs to re-render or `false` to avoid being re-render.
**Syntax:**
```js
shouldComponentUpdate(nextProps, nextState){ }
```
**Example:**
```js
/**
* Prevent a component from rendering
*/
export default class App extends React.Component {
constructor() {
super();
this.state = {
countOfClicks: 0
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
countOfClicks: this.state.countOfClicks + 1
});
}
shouldComponentUpdate(nextProps, nextState) {
console.log("this.state.countOfClicks", this.state.countOfClicks);
console.log("nextState.countOfClicks", nextState.countOfClicks);
return true;
}
render() {
return (
shouldComponentUpdate Example
Count of clicks: {this.state.countOfClicks}
);
}
}
```
## Q. What is Compound Components in React?
A compound component is a type of component that manages the internal state of a feature while delegating control of the rendering to the place of implementation opposed to the point of declaration. They provide a way to shield feature specific logic from the rest of the app providing a clean and expressive API for consuming the component.
Internally they are built to operate on a set of data that is passed in through children instead of props. Behind the scenes they make use of React\'s lower level API such as `React.children.map()`, and `React.cloneElement()`. Using these methods, the component is able to express itself in such a way that promotes patterns of composition and extensibility.
**Example:**
```js
function App() {
return (
)
}
```
In this example, the `
);
}
```
**Example:**
```js
/**
* React Lazy Loading Routes
*/
import React, { Suspense, lazy } from "react";
import { Switch, BrowserRouter as Router, Route, Link } from "react-router-dom";
const Home = lazy(() => import("./Home"));
const ContactUs = lazy(() => import("./ContactUs"));
const HelpPage = lazy(() => import("./Help"));
export default function App() {
return (
- Home
- ContactUs
- HelpPage
Loading...
` displays data using props while the `` takes its data from the internal state of the ExampleComponent.
## Q. What is the difference between Component and Container in React?
The **presentational** components are concerned with the look, **container** components are concerned with making things work.
For example, this is a presentational component. It gets data from its props, and just focuses on showing an element
```js
/**
* Presentational Component
*
**/
const Users = props => (
{props.users.map(user => (
- {user}
))}
)
```
On the other hand this is a container component. It manages and stores its own data, and uses the presentational component to display it.
```js
/**
* Container Component
*
**/
class UsersContainer extends React.Component {
constructor() {
this.state = {
users: []
}
}
componentDidMount() {
axios.get('/users').then(users =>
this.setState({ users: users }))
)
}
render() {
return
}
}
```
## Q. How would you prevent a component from rendering?
React **shouldComponentUpdate()** is a performance optimization method, and it tells React to avoid re-rendering a component, even if state or prop values may have changed. This method only used when a component will stay static or pure.
The React `shouldComponentUpdate()` method return `true` if it needs to re-render or `false` to avoid being re-render.
**Syntax:**
```js
shouldComponentUpdate(nextProps, nextState){ }
```
**Example:**
```js
/**
* Prevent a component from rendering
*/
export default class App extends React.Component {
constructor() {
super();
this.state = {
countOfClicks: 0
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
countOfClicks: this.state.countOfClicks + 1
});
}
shouldComponentUpdate(nextProps, nextState) {
console.log("this.state.countOfClicks", this.state.countOfClicks);
console.log("nextState.countOfClicks", nextState.countOfClicks);
return true;
}
render() {
return (
shouldComponentUpdate Example
Count of clicks: {this.state.countOfClicks}
);
}
}
```
## Q. What is Compound Components in React?
A compound component is a type of component that manages the internal state of a feature while delegating control of the rendering to the place of implementation opposed to the point of declaration. They provide a way to shield feature specific logic from the rest of the app providing a clean and expressive API for consuming the component.
Internally they are built to operate on a set of data that is passed in through children instead of props. Behind the scenes they make use of React\'s lower level API such as `React.children.map()`, and `React.cloneElement()`. Using these methods, the component is able to express itself in such a way that promotes patterns of composition and extensibility.
**Example:**
```js
function App() {
return (
)
}
```
In this example, the `
-
{props.users.map(user => (
- {user} ))}
shouldComponentUpdate Example
Count of clicks: {this.state.countOfClicks}
- Home
- ContactUs
- HelpPage
Render Props Counter
{count}
{this.props.render({ increment: this.increment, count: count })}
);
}
}
```
**
## Q. How do you create Higher Order Component using render props?
It is possible to implement most higher-order components (HOC) using a regular component with a render prop. This way render props gives the flexibility of using either pattern.
**Example:**
```js
function withMouse(Component) {
return class extends React.Component {
render() {
return (
React Children Props Example
{this.props.children}Other Component Props
;
}
}
ReactDOM.render(
React DOM Props
{/* Children Props*/}Test
);
```
**Solution:** By creating props specifically for DOM attribute, we can safely spread.
```js
const Sample = () => (Test
);
```
Or alternatively we can use prop destructuring with `...rest`:
```js
const Sample = () => (Test
);
```
**Note:**
*In scenarios where you use a PureComponent, when an update happens it re-renders the component even if domProps did not change. This is because PureComponent only shallowly compares the objects.*
## Q. When should I be using React.cloneElement vs this.props.children?
The `React.cloneElement` only works if your child is a single React element.
**Example:**
```js
Users
{this.props.children}
Content Here
```
It is equal to Class Component
```js
const person = {
name: "Alex",
age: 26,
country: "India"
}
class SpreadExample extends React.Component {
render() {
const {name, age, country} = {...this.props}
return (
Person Information:
- name={name}
- age={age}
- country={country}
{this.state.name}
; } } ``` ** ## Q. How to change the state of a child component from its parent in React? To change child component\'s state from parent component with React, we can pass props. ```js /** * Change Child state from its Parent * @param {*} param0 */ const Child = ({ open }) => { returnChild State: {open.toString()}
; }; const Parent = () => { const [isOpen, setIsOpen] = React.useState(false); const toggleChild = () => { setIsOpen((prevValue) => !prevValue); }; return (
{/* Pass a callback to Child */}
);
};
export default Parent;
```
## Q. How to pass a parameter to event handlers in React?
**Example:**
```js
const message = "Hey there!";
export default class App extends React.Component {
displayMessage(message) {
alert(message);
}
render() {
return (
);
}
}
```
## Q. How do you pass an event handler to a component?
**Example:**
```js
import React, {useState} from "react";
import "./styles.css";
export default function App() {
return (
Counter: {counter}
{this.state.count}
);
}
}
```
**3. RequestAnimationFrame Throttling:**
The **requestAnimationFrame** is a way of queuing a function to be executed in the browser at the optimal time for rendering performance. A function that is queued with requestAnimationFrame will fire in the next frame. The browser will work hard to ensure that there are 60 frames per second (60 fps). However, if the browser is unable to it will naturally limit the amount of frames in a second.
For example, a device might only be able to handle 30 fps and so you will only get 30 frames in that second. Using requestAnimationFrame for throttling is a useful technique in that it prevents you from doing more than 60 updates in a second. If you are doing 100 updates in a second this creates additional work for the browser that the user will not see anyway.
```js
/**
* RequestAnimationFrame Throttling
*/
import rafSchedule from "raf-schd";
import React from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
// Create a new function to schedule updates.
this.scheduleUpdate = rafSchedule((point) => this.props.onScroll(point));
}
handleScroll(e) {
// When we receive a scroll event, schedule an update.
// If we receive many updates within a frame, we'll only publish the latest value.
this.scheduleUpdate({ x: e.clientX, y: e.clientY });
}
componentWillUnmount() {
// Cancel any pending updates since we're unmounting.
this.scheduleUpdate.cancel();
}
render() {
return (
this.inputElement = input} />
)
}
handleClick = (e) => {
this.inputElement.click()
}
}
```
*Note: The `ES6 arrow function` provides the correct lexical scope for `this` in the callback.*
## Q. How to listen for click events that are outside of a component?
**Example:**
```js
class OutsideAlerter extends Component {
// ...
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Set the wrapper ref
*/
setWrapperRef(node) {
this.wrapperRef = node;
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return {this.props.children}
;
}
}
OutsideAlerter.propTypes = {
children: PropTypes.element.isRequired
};
```
## Q. How to convert text to uppercase on user input entered?
```js
import React, { useState } from "react"
import ReactDOM from "react-dom"
const toInputUppercase = e => {
e.target.value = ("" + e.target.value).toUpperCase()
}
const App = () => {
const [name, setName] = useState("")
return (
setName(e.target.value)}
onInput={toInputUppercase} // apply on input which do you want to be capitalize
/>
)
}
ReactDOM.render(React List
-
{this.state.lists.map((list) => (
- {list.context} ))}
Render Array List
{items.map((item, index) => ({item.name}
))}
Render String List
{["test", "render", "array", "list"]}Render Number List
{numbers.map((item, index) => ({item}
))}
-
{users.map((user) => (
- ))}
{users.length > 0 && (
);
}
```
## Q. How does Axios Interceptors work in React?
Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check response status code for every response that is being received.
Interceptors are methods which are triggered before or after the main method. There are two types of interceptors:
**1. Request Interceptor:**
It allows you to write or execute a piece of your code before the request gets sent. For example, an authentication token could be injected into all requests.
**Example:**
```js
// Request Handler
const requestHandler = (request) => {
const token = localStorageService.getAccessToken()
if (token) {
request.headers['Authorization'] = 'Bearer ' + token
}
return request
}
// Request Interceptor
axios.interceptors.request.use(
request => requestHandler(request)
)
```
**2. Response Interceptor:**
It allows you to write or execute a piece of your code before response reaches the calling end.
**Example:**
```js
// Response Handlers
const errorHandler = (error) => {
if (isHandlerEnabled(error.config)) {
// Handle errors
}
return Promise.reject({ ...error })
}
const successHandler = (response) => {
if (isHandlerEnabled(response.config)) {
// Handle responses
}
return response
}
// Response Interceptors
axios.interceptors.response.use(
response => successHandler(response),
error => errorHandler(error)
)
```
## Q. How to do caching in React?
In React, caching data can be achieved in multiple ways
* Local Storage
* Redux Store
* Keep data between mouting and unmounting
* useMemo()
**1. Memoizing Fetched Data:**
Memoization is a technique we would use to make sure that we don\'t hit the API if we have made some kind of request to fetch it at some initial phase. Storing the result of expensive fetch calls will save the users some load time, therefore, increasing overall performance.
**Example:**
```js
const cache = {}
const useFetch = (url) => {
const [status, setStatus] = useState('idle')
const [data, setData] = useState([])
useEffect(() => {
if (!url) return
const fetchData = async () => {
setStatus('fetching')
if (cache[url]) {
const data = cache[url]
setData(data)
setStatus('fetched')
} else {
const response = await fetch(url)
const data = await response.json()
cache[url] = data // set response in cache
setData(data)
setStatus('fetched')
}
}
fetchData()
}, [url])
return { status, data }
}
```
Here, we\'re mapping URLs to their data. So, if we make a request to fetch some existing data, we set the data from our local cache, else, we go ahead to make the request and set the result in the cache. This ensures we do not make an API call when we have the data available to us locally.
**2. Memoizing Data With useRef():**
With `useRef()`, we can set and retrieve mutable values at ease and its value persists throughout the component\'s lifecycle.
```js
const useFetch = (url) => {
const cache = useRef({})
const [status, setStatus] = useState('idle')
const [data, setData] = useState([])
useEffect(() => {
if (!url) return
const fetchData = async () => {
setStatus('fetching')
if (cache.current[url]) {
const data = cache.current[url]
setData(data)
setStatus('fetched')
} else {
const response = await fetch(url)
const data = await response.json()
cache.current[url] = data // set response in cache
setData(data)
setStatus('fetched')
}
}
fetchData()
}, [url])
return { status, data }
}
```
**3. Using localStorage():**
```js
const InitialState = {
someState: 'a'
}
class App extends Component {
constructor(props) {
super(props)
// Retrieve the last state
this.state = localStorage.getItem("appState") ? JSON.parse(localStorage.getItem("appState")) : InitialState
}
componentWillUnmount() {
// Remember state for the next mount
localStorage.setItem('appState', JSON.stringify(this.state))
}
render() {
...
}
}
export default App
```
**4. Keep data between Mouting and Unmounting:**
```js
import React, { Component } from 'react'
// Set initial state
let state = { counter: 5 }
class Counter extends Component {
constructor(props) {
super(props)
// Retrieve the last state
this.state = state
this.onClick = this.onClick.bind(this)
}
componentWillUnmount() {
// Remember state for the next mount
state = this.state
}
onClick(e) {
e.preventDefault()
this.setState(prev => ({ counter: prev.counter + 1 }))
}
render() {
return (
-
{users.map((user) => (
- {user.name} ))}
{ this.state.counter }
)
}
}
export default Counter
```
## Q. How to use async await in React?
**Example:**
```js
class App extends Component {
// ...
async componentDidMount() {
try {
const response = await fetch(`https://api.github.com/users`);
if (!response.ok) {
throw Error(response.statusText);
} else {
const json = await response.json();
this.setState({ data: json });
}
} catch (error) {
console.log(error);
}
}
render() {
return (
-
{this.state.data.map((el) => (
- {el.login} ))}
User Details
Name:{location.state.name}
Email:{location.state.email}
>
);
}
/**
* User Component
*/
function User() {
return (
);
}
/**
* App Component
*/
export default function App() {
return (
Greetings Page
{text}
> ); } const RouterExample = () =>Home Page
; const App = () => (Home Greeting
- Home
- Contact Us
- Help
Parameter: {id}
; } ``` ## Q. What is the difference between HashRouter and BrowserRouter in React? **1. BrowserRouter:** * The widely popular router and a router for modern browsers which user HTML5 pushState API. (i.e. `pushState`, `replaceState` and `popState` API). * It routes as normal URL in browser, you can\'t differentiate whether it is server rendered page or client rendered page through the URL. * It assumes, your server handles all the request URL (eg., `/`, `/about`) and points to root `index.html`. From there, BrowserRouter take care of routing the relevant page. * It accepts `forceRefresh` props to support legacy browsers which doesn\'t support HTML5 pushState API **Syntax:** ```js /** * https://example.com/home * https://example.com/about */Home Page
; }; const AboutPage = () => { returnAbout Page
; }; export default function App() { return (- Home
- About
Home Page
; }; const AboutPage = () => { returnAbout Page
; }; export default function App() { return (- Home
- About
Something went wrong.
; } return this.props.children; } } ``` Here, We have a state object having two variables `isErrorOccured` and `errorMessage` which will be updated to true if any error occurs. ## Q. What are the methods invoked during error handling? To create an error boundary, we simply have to create a class component and define a state variable for determining whether the error boundary has caught an error. Our class component should also have at least three methods: * A static method called **getDerivedStateFromError()**, which is used to update the error boundary\'s state * A **componentDidCatch()** lifecycle method for performing operations when our error boundaries catch an error, such as logging to an error logging service * A **render()** method for rendering our error boundary\'s child or the fallback UI in case of an error **Example:** ```js /** * Error Boundary in React */ class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true }; } componentDidCatch(error, errorInfo) { // You can also log the error to an error reporting service logErrorToMyService(error, errorInfo); } render() { if (this.state.hasError) { // You can render any custom fallback UI returnSomething went wrong.
; } return this.props.children; } } ``` ## Q. What do you understand by refs in React? The **Refs** provide a way to access DOM nodes or React elements created in the render method. React `Refs` are a useful feature that act as a means to reference a DOM element or a class component from within a parent component. Refs also provide some flexibility for referencing elements within a child component from a parent component, in the form of **ref forwarding**. **Example:** ```javascript /** * Refs */ class App extends React.Component { constructor(props) { super(props) // create a ref to store the textInput DOM element this.textInput = React.createRef() this.state = { value: '' } } // Set the state for the ref handleSubmit = e => { e.preventDefault() this.setState({ value: this.textInput.current.value }) } render() { return (React Ref - createRef
{/** This is what will update **/}Value: {this.state.value}
{arr.map((item, index) => {
return (
);
}
```
## Q. What is the difference between useRef() and createRef()?
**1. useRef():**
The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn\'t create a new instance of the ref for every re-render. It persists the existing ref between re-renders.
**Example:**
```js
/**
* useRef()
*/
export default function App() {
const [count, setCount] = useState(0);
const ref = useRef();
useEffect(() => {
ref.current = "SomeInitialValue";
}, []);
useEffect(() => {
console.log(count, ref.current);
}, [count]);
return (
{
refs.current[index] = element;
}}
>
{item}
);
})}
{count}
{count}
I'm a real component too
Especially with useImperativeMethods
null
in DevTools
** ## Q. Explain Composition in React? Composition is also a familiar concept in Object Oriented Programming. Instead of inheriting properties from a base class, it describes a class that can reference one or more objects of another class as instances. **Example:** ```js /** * Composition in React */ import React, { useState } from "react"; import Name from "./Name"; export default function App() { const [name, setName] = useState(""); return ( ); } ``` ```js /** * Name Component * @param {*} param0 - name * @param {*} param1 - setName */ export default function Name({ name, setName }) { return (
setName(event.target.value)} />
);
}
```
## Q. How to use styles in React.js?
React Components can add styling in the following ways:
**1. Inline Styling:**
In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects also use curly braces, the styling in the example above is written inside two sets of curly braces `{{}}`. Since the inline CSS is written in a JavaScript object, properties with two names, like `background-color`, must be written with camel case syntax:
**Example:**
```js
/**
* Inline Styling
*/
class HeaderComponent extends React.Component {
render() {
return (
Header Component Style!
Add a little style!
Header Component Style!
Add a little style!
Header Component Style!
Add a little style!.
Header Component Style!
Add a little style!.
Example Text
} } ``` ** ## Q. What are styled components? The `Styled-components` is a CSS-in-JS styling framework that uses tagged template literals in JavaScript and the power of CSS to provide a platform that allows you to write actual CSS to style React components. The `styled-components` comes with a collection of helper methods, each corresponding to a DOM node for example `