User FAQs - React
If you have a question, please send it to us.
1) What is React ?
React is a JavaScript library for building web applications with rich user interfaces.
In the context of MVC (Model View Controller), React is just the View.
It simplifies the creation of complicated UIs by using reusable components.
React is designed for Single Page Applications and replaces JQuery.
Cross platform, open source, free and easy to integrate into existing projects.
It can be used for both client and server side rendering.
2) What is the difference between Client vs Server Side Rendering ?
Client side - pulls an initial HTML page with a large JavaScript file and then uses the browser to dynamically render the finished HTML page using JavaScript.
Server side - pulls a complete HTML page with a small JavaScript file that is only used to make the page interactive.
3) Is React a Functional or Object Orientated programming language ?
JavaScript is functional, but does support some object orientated techniques.
React is functional, but does support some object orientated techniques.
C# is object orientated, but does support some functional techniques.
Functional programming is more declarative. Object Orientated is more imperative.
Functional programming is more abstract and at a higher level that object orientated.
JQuery followed a more imperative approach when working with the DOM.
VBA is imperative and is very procedural.
Functional focuses on Composition. Object Orientated focuses on Inheritance.
4) What are the differences between React and Angular ?
React is a library (created by Facebook), Angular is a framework (created by Google).
React uses the Virtual DOM, Angular uses the Real DOM.
React requires additional libraries for complex features (for example routing), Angular provides a lot of built-in features.
React is based on JavaScript, Angular is closer to TypeScript.
5) Are there any project templates or boilerplates for common React projects ?
Yes, there are 3 main ones:
[[Create React App]] - can generate a single page application that renders client side.
Gatsby - can generate a static website with multiple pages.
Next.js - can generate a dynamic website that includes routing as well as both client and server side rendering.
6) What are the main features of React ?
Very fast because only the changed components are updated and not the full page.
Uses one-way data binding (or data-flow). Data only flows from top to bottom.
In Two-way binding there is a tight coupling between the model and the view, which React does not have.
Relatively straight forward to debug because everything is broken down into components (or functions) which are independent and can be easily reused.
It can use the JSX extension which allows for HTML and JavaScript to exist in the same file, meaning the presentation and the business logic is all in one place.
7) What is the DOM ?
Short for Document Object Model.
This represents the page as a tree-like structure which allows JavaScript to dynamically access and manipulate the content and structure of the page.
The DOM is an object orientated representation of the document (or page) in memory.
8) What is the Virtual DOM ?
The Virtual DOM is an in-memory representation of the Real DOM.
React uses the Virtual DOM to update only the parts of the Real DOM that have changed.
The representation of the UI is kept in memory and sync'ed with the Real DOM.
Extra step between the rendering and the elements being displayed on the screen.
This entire process is called reconciliation.
9) What is JSX ?
This is a JavaScript XML syntax designed to simplify working with React components.
This looks like HTML but has been extended with an additional syntax to allow you to insert JavaScript into your HTML.
React uses the Babel extension (which is a JavaScript compiler) to transpile JSX into Javascript which the browser understands.
Each JSX element is just syntactic sugar for calling React.createElement.
Anything you can write with JSX can be written with JavaScript.
JSX lets you include JavaScript expressions by putting them inside curly brackets.
return <div>Hello {this.props.myName}</div>;
return React.createElement('div', null, 'Hello ' + {this.props.myName});
The JSX syntax also provides some type safety as incorrect html tags will be indicated at design-time.
10) Can you give some examples of embedded JavaScript inside JSX ?
You can use JSX inside if statements, for loops, assign it to variables, accept it as arguments, return it from functions.
const R_Comp = () =>{
function f_fullName(user) { return user.firstName + ' ' + user.lastName; };
const myObject = { firstName: 'Mat', lastName: 'Smith' };
return ( <h1>{ f_fullName(myObject) }</h1> );
};
Notice this is "backgroundColor" and not "background-color"
return <h1 style={{backgroundColor:'yellow'}}>Hello Style!</h1>
Notice this uses a classname provided by a prop.
<dic className = {this.props.className} >
11) Why does the HTML tag use className and not "class" in JSX ?
This is because class is a reserved keyword in JavaScript.
In React, className is used to style an element.
return (
<div className='item-list'>
12) What is ReactDOM.render() ?
The ReactDOM.render is used to render the component directly into a DOM element.
The render method creates a new instance of the MyComp component, calls its render method, and then updates the DOM to match the rendered output.
import ReactDOM from 'react-dom';
ReactDOM.render(<R_Comp />, document.getElementById('root') );
13) What is ReactDOM.createRoot() ?
The createRoot method was added in October 2020 (React 17) to provide better performance and better support for concurrent mode.
This method creates a new root container that lets you run multiple calls to render using the same DOM element container.
import { createRoot } from 'react-dom/client';
const root = createRoot( document.getElementById('root') );
root.render(<R_Comp />);
14) What is the difference between an Element and a Component ?
A component is a function (or a class) that returns a single React element.
All component names should be written in PascalCase (capitalizing the first letter of each word).
An element is an object that describes an html component and its corresponding properties.
15) Is it possible to return more than one element from a component ?
Yes. If a component needs to return multiple elements then the React.Fragment tag can be used.
Ths is often used when you want to embed components.
You could use a <div> tag however adding extra nodes to the DOM might change the appearance or layout of the page.
This syntax does support the key attribute.
const R_Comp1 = (props) => {
return (
<React.Fragment>
<h1>Title</h1>
<R_Comp2 />
</React.Fragment>
);
}
There is a shorthand syntax for this <> </>
This shorthand does not support the key attribute or any other attributes.
return (
<>
<div/>
<div/>
</>
16) Is it possible to run JavaScript code inside the return ?
Yes. It needs to be inside curly brackets and you must make sure the return only returns a single element.
const R_Comp = (props) => {
return (
<div>
<h1>test</h1>
{ console.log('test') }
</div>
)
};
17) What is State ?
State holds the information that you need to use (or keep) within the component.
State can be changed by the component iteself (mutable)
The parent component cannot change it.
An initial value can be defined inside the component.
Before functional components you had to use a class (alongside the "this" keyword) to hold state.
A class could be created in 2 ways, either using the built-in ES 2015 class keyword or by using React.createClass.
18) What are Props ?
Props allows us to pass information from a parent component into a child component.
Props are read-only and cannot be changed by the component itself (immutable).
Props can be passed in individually and should always be enclosed in curly brackets.
You can pass a string and omit the curly brackets but this is confusing
const R_Comp = (props) => {
console.log( props.property1 );
return ( <h1> {props.property1} </h1> );
}
ReactDOM.render(<R_Comp property1={'text'} />, document.getElementById('root'));
ReactDOM.render(<R_Comp property1={100} />, document.getElementById('root'));
This destructures the incoming props into specific variables.
const R_Comp = (props) => {
const { property1 } = props;
return ( <h1>{ property1 }</h1> );
}
This is equivalent to destructuring the argument
const R_Comp = ({ property1 }) => {
19) Is it possible to pass in more than one prop into a component ?
Yes. You can pass in more than one prop using lots of different methods.
You can pass multiple parameters to a component but a Functional component can only accept one parameter.
Multiple props can be passed in as an object using curly brackets.
const R_Comp = (props) => {
console.log( myObjectProps.property1 );
return (<h1> {myObjectProps.property2} </h1>);
}
const myObjectProps = {
property1: 'text',
property2: 100
}
ReactDOM.render(<R_Comp MyProps={myObjectProps} />, ..);
If you want to pass the object inline, you need to include 2 curly brackets.
ReactDOM.render(<R_Comp MyProps={{ property1: 'text', property2: 100 }} />, ..);
Instead of accepting a props object you could use the spread operator (...) to go straight to the object.
const R_Comp = (...props) => {
console.log( myObjectProps.property1 );
return (<h1> {myObjectProps.property2} </h1>);
}
const myObjectProps = {
property1: 'text',
property2: 100
}
ReactDOM.render(<R_Comp MyProps={myObjectProps} />, ..);
Multiple props can be passed in individually and destructuring can be used to .
const R_Comp = ({ Prop1 , Prop2 }) => {
console.log( Prop1 );
return (<h1> {Prop2} </h1>);
}
ReactDOM.render(<R_Comp Prop1={'text'} Prop2={100} />, ..);
Instead of passing the props in seperately you can combine the spread operator with destructuring.
For this to work the names of the properties and variables must be identical.
const R_Comp = ({ property1 , property2 }) => {
console.log( property1 );
return (<h1> {property2} </h1>);
}
const myObjectProps = {
property1: 'text',
property2: 100
}
ReactDOM.render(<R_Comp {...myObjectProps} />, ..);
20) Why should you avoid copying the values of props into a component's state ?
Because that would create two instances of the same state that could become out of sync .
21) What is the children prop ?
A property that lets you nest components in other components .
22) What is an Event in React ?
An event is an action that can be triggered by a user or system event such as pressing a key, mouse click etc
Avoid using inline event handlers: While it is possible to define event handlers inline, it is considered bad practice because it can make your code harder to read and maintain.
In HTML, you need to invoke the function by appending ()
In React you do not append () to the function name (or class method).
In HTML, the event name (onclick) is usually written in lowercase.
<button onclick="f_handleClick()"></button>
In React the event name (onClick) is usually written in camelCase.
<button onClick={f_handleClick}>
23) What is a Synthetic Event in React ?
React uses synthetic events to handle events from button, input and form elements.
A synthetic event is a shell around the native DOM event with additional information for React.
our event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser's native event.
If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it. The synthetic events are different from, and do not map directly to, the browser's native events. F
This is an object which acts as a cross-browser wrapper around the browsers native event
It combines the behaviour of different browsers native events into one API and this makes sure that the events are consistent across different browsers.
const R_Comp = (props) => {
function f_handleClick(event) {
event.preventDefault();
console.log('clicked');
}
return (
<a href="#" onClick={f_handleClick}>
Click Me
</a>
);
}
24) How can I prevent event default behaviour ?
In React you must call preventDefault() explicitly.
In some cases, you may want to prevent the default behavior of an event, such as submitting a form or following a link. You can do this using the event.preventDefault() method in your event handler function.
function f_handleClick(event) {
event.preventDefault();
console.log("The link was clicked.");
}
25) What steps do you need to take when building a React App ?
Step 1 - Split the UI in different components and decide on the component hierarchy
Step 2 - Build a static version of the app using only props (no state because nothing is interactive). Build bottom up. Start creating the children at the bottom of the file working up with parents above children.
Step 3 - Describe the different visual states for each component. Identify what is state in your app. If it remains unchanged, is passed in from a parent or can be calculated then it is not state.
Step 4 - Identify where the states should live and which component should own them.
Step 5 - Add any necessary data flow from children to parents. Create the corresponding state handler functions and pass them as props to the children.
26) What is a Functional Component ?
Hooks were added in February 2019 (React 16.8) to provide a way of handlying state without needing to use classes or the "this" keyword.
Functions have always been able to handle props
There is no need for a render function, the element can just be returned.
We do not need to use the 'this' keyword.
A props arguments can always be included even when there are no props being passed in.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script type="text/babel">
const R_Comp = (props) => {
const [s_color, sf_setColor] = React.useState('red');
const [s_counter, sf_setCounter] = React.useState(0);
function f_handleClick() {
sf_setColor('blue');
};
function f_handleIncrement() {
sf_setCounter(s_counter + 1);
sf_setColor('blue');
};
function f_handleDecrement() {
sf_setCounter(s_counter - 1);
};
function f_handleResetCount() {
sf_setCounter(0);
};
return (
<div>
<h1 style = { {color: s_color} }>{props.Prop1} {s_counter}</h1>
<button onClick={f_handleIncrement}>Increment</button>
<button onClick={f_handleDecrement}>Decrement</button>
<button onClick={f_handleResetCount}>Reset</button>
</div>
);
};
ReactDOM.render(<R_Comp Prop1={'text'}/>, document.getElementById('root'));
Notice the h1 style uses one set of curly brackets because its an object and then another set of curly brackets because its JSX.
27) Can we use a prop to initialise the value of a state ?
Yes, but do not put the prop inside curly brackets.
const R_Comp = (props} ) => {
const [s_color, sf_setColor] = React.useState(props.color);
28) Can we declare a functional component using the "function" keyword instead of "const" ?
function R_Comp(props) {
29) Can we declare the event handlers using the "const" keyword instead of "function" ?
const f_handleClick = () => {
30) Can we define a component on a single line ?
const R_Comp = ({ property1 }) => <h1>{property1}</h1/>;
31) Can you describe the Lifecycle for a functional component ?
Every component has a lifecycle which can monitor and manipulate
useEffect method.
32) What are Hooks ?
Before Hooks were added functional components could not hold state.
Hooks are functions that allow us to hook into and manage state. (useHOOKNAME)
Hooks cannot be conditional.
Hooks can only be called at the top level of a component
[[List all Hooks]]
33) How do you Change the State in a functional component ?
The useState hook can be used.
It returns an array with two values.
The current state and a function to update the state.
The hook takes an initial state value as an argument and returns an updated state value whenever the setter function is called.
34) How can a child component update the state in a parent component ?
We can create a state handler function in the parent component and pass it down to the child component as a prop.
const R_Parent = (props) => {
const [svalue, sf_setValue] = React.useState(props.pInitialText);
function f_UpdateStateCallback(newValue) {
console.log('callback - ' + newValue);
sf_setValue(newValue);
}
return (
<R_Child p_InitialText={props.pInitialText}
p_FunctionUpdateState={f_UpdateStateCallback} />
)
};
const R_Child = ({ p_InitialText, p_FunctionUpdateState }) => {
function f_handleChange(e) {
e.preventDefault();
p_FunctionUpdateState(e.target.value);
};
return (
<div>
<form>
<input type="text"
placeholder={p_InitialText}
onChange={f_handleChange}
/>
</form>
</div>
)
};
ReactDOM.render(<R_Parent pInitialText={'better'} />,
document.getElementById('root'));
35) What does the useReducer hook do ?
It allows for custom state logic.
this hook can also be used to manage the state of a component.
useReducer is a more powerful hook for managing complex state with multiple values.
36) What does the useEffect hook do ?
This tells React that your component needs to do something after it has been rendered.
This is then called after the DOM has updated.
import { useEffect, useState } from 'react';
React.useEffect( () => {
document.title = 'Update Title';
});
const R_Comp = () => {
const [data, setData] = React.useState( [] );
React.useEffect( () => {
setData( getData() )
}, [] );
return <R_DisplayData data={ data } />
}
37) Will the useEffect hook run after every render ?
Yes, by default it runs after the first render and after subsequent renders.
If you pass an empty array [] as a second argument it tells React that the effect does not depend on any values from props or state so it only needs to run on the first render.
38) How would you delay an API call until a class component has mounted ?
In a functional component you can use hooks
useEffect hook and pass an empty array
39) What does the useRef hook do ?
The useRef hook allows you to persist values between renders.
40) What does the useMemo hook do ?
The useMemo hook returns a memoized value.
41) What does the useCallback hook do ?
The useCallback hook returns a memoized callback function.
42) What is a Custom Hook ?
When you have component logic that needs to be used by multiple components, we can extract that logic to a custom hook.
Custom hooks are reusable functions (useHOOKNAME).
Examples of custom hooks are:
useFetch, useArray, useLocalStorage
43) Write some code to display a List using the key attribute ?
The 'key' attribute needs to always be included when there is a dynamically generated list of items.
You need to use the "key" identifier. Keys must be a unique number or string
This identifer needs to be unique and is used to identify which items have changed, updated or deleted from the list.
Using it allows elements to be reordered instead of rerendered.
Passing a list into a child component
Traversing a list is done using the built-in map function.
const myObject = [
{id: '1', value: 'London'},
{id: '2', value: 'New York'},
{id: '3', value: 'Tokyo'}
];
const R_ListItem = (props) => {
return (
<li>{props.value}</li>
);
};
const R_List = (props) => {
const cities = props.p_Cities;
const listItems = cities.map( (city) =>
<R_ListItem key={city.id}, value={city.value} />
);
return (
<ul>{listItems}</ul>
);
};
ReactDOM.render(<R_List p_Cities={myObject} />,
document.getElementById('root') );
Adding the key here is also used but not as good ??
const listItems = cities.map( (city) => (
<li key={city.id}>
{city.value}
</li>
);
When you don't have stable IDs for rendered items or you just have a static list, you can use the item 'index' as the key.
When indexes are used as keys reordering a list, or adding and removing items from a list may be problematic so this is not recommended.
const listItems = cities.map( (city, index) => (
<li key={index}>
{city.value}
</li>
));
44) What is Conditional Rendering ?
You can create distinct components that encapsulate all the behaviour they need.
It is then possible to render only some of the components depending on the state of the application
React has no special syntax for adding conditions, so you can use the JavaScript syntax.
const R_Comp1 = (props) => {
const isLoggedIn = props.p_IsLoggedIn;
if (isLoggedIn == true) {
return <R_Comp2 />;
}
return <R_Comp3 />;
}
}
// using the ternary operator
isLoggedIn ? return <R_Comp2 /> : return <R_Comp3 />
// logical && operator
isLoggedIn && Return <R_Comp2 />
You should not use && if you are checking the length of a string and it could be zero and this will be assumed to be False.
If the length is zero nothing will be called and null is returned ??
45) How can you prevent a component from being rendered ?
It is possible to hide a component even though it has been rendered by another component.
This can be done by returning null;
const R_Comp = (props) => {
if (props.Prop1 == false) {
return null;
}
return (
<div>
<h1>Success</h1>
</div>
);
};
ReactDOM.render(<R_Comp Prop1 />, document.getElementById('root') );
46) When would you use Suspense ?
Added in React 16.6.
If a component needs several seconds to render you can render something else while the content is loading/
<Suspense fallback={ < Loading /> } >
< R_LargeComponent />
</Suspense>
47) What option does "Suspense" use to load a component when a targeted component is not ready to render ?
48) When would you use React.StrictMode ?
This is a developer tool for highlighting potential problems in an application.
React.StrictMode is similar to the "use strict" syntax in JavaScript.
import { StrictMode } from "React";
<React.StrictMode>
< SuspiciousCode />
</React.StrictMode>
React 18.0 introduced a new development only check to StrictMode.
This new check will automatically mount and unmount every component whenever a component mounts for the first time, restoring the previous state on the second mount.
49) What is the difference between createElement and cloneElement ?
JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI.
Whereas cloneElement is used to clone an element and pass it new props.
50) What is a Class Component ?
A class component is a JavaScript class that extends React.Component and returns a single React element inside a render method. Website - legacy.reactjs.org
These were introduced in June 2015 as part of ES 2015.
Every property or method that is a function is NOT bound automatically. These must be binded manually.
We do not need to use the function keyword to define methods.
Props are explicitly passed through the constructor.
The propTypes has now changed to just an Object property on the class.
The getDefaultProps has now changed to just an Object property on the class called defaultProps, as it's no longer a "get" function, it's just an Object.
The getInitialState was removed and all state manipulation is done through the constructor.
We need to explicitly bind "this" to methods inside the constructor.
These classes do not support inheritance. mixins are not supported in ES 2015 classes
Every class must contain a render function.
class R_Comp extends React.Component{
constructor(props) {
super(props);
this.state = {
s_color: 'red',
s_counter: 0
};
this.m_handleIncrement = this.m_handleIncrement.bind(this);
this.m_handleDecrement = this.m_handleDecrement.bind(this);
this.m_handleResetCount = this.m_handleResetCount.bind(this);
};
componentDidMount() {
console.log('runs after the mount');
};
m_handleIncrement() {
this.setState({
s_counter: this.state.s_counter + 1,
s_color: 'blue'
});
};
m_handleDecrement() {
this.setState(previousState => ({
s_counter: previousState.s_counter - 1
}));
};
m_handleResetCount() {
this.setState( {s_counter: 0} );
};
const myObject = {
color: s_color
}
render() {
return (
<div>
<h1 style={myObject}>{this.props.Prop1} {this.state.s_counter}</h1>
<button onClick={this.m_handleIncrement}>Increment</button>
<button onClick={this.m_handleDecrement}>Decrement</button>
<button onClick={this.m_handleResetCount}>Reset</button>
</div >
);
}
};
ReactDOM.render(<R_Comp Prop1={'text'}/>, document.getElementById('root'));
You can assign a special "propTypes" property. This is the syntax after React 15.5. Before React 15.5 this was available from React.PropTypes.
import PropTypes from 'prop-types';
R_Comp.propTypes = {
Prop1: PropTypes.string
};
R_Comp.defaultProps = {
Prop1: 'blank'
};
Since ES2022 you are able to declare defaultProps as a static property within a React component class.
class R_Comp extends React.Component{
static defaultProps = {
Prop1: 'blank'
}
};
51) Can we declare the event handlers using the "function" keyword ?
No. Classes can only contain methods, they cannot contain functions.
52) How can you bind the properties and methods of the class ?
These have to be explicitly bound and can either be done in the constructor or inline.
There is one way this can be done in the constructor.
<button onClick = { this.m_handleClick.bind(this) } >Change</button>
There are two ways this can be done inline.
<button onClick = { this.m_handleClick.bind(this) } >Change</button>
<button onClick = { () = > this.handleClick() } >Change</button>
Another alternative to inline binding is to actually change the function declaration to use an Arrow function.
m_handleClick() { // needs explicit binding
m_handleClick = () => { // automatic binding
Putting the bindings in the constructor is more efficient because the binding will be done once, instead of every time the render is called.
53) How can you pass parameters to event handlers ?
This does the binding inline and uses an arrow function
m_handleClick(arg1) {
};
<button onClick={ () => this.m_handleClick.bind(arg1) } />
<button onClick={ (e) => this.m_handleClick.bind(arg1, e) } />
This does the binding inline
m_handleClick(arg1) {
};
<button onClick={ this.m_handleClick.bind(this, arg1) } />
<button onClick ??
This uses an arrow function declaration to do automatic binding.
m_handleClick = (arg1) => {
};
<button onClick={ this.m_handleClick(arg1) } />;
<button onClick ??
54) This is used with OfficeJS - is it passing in additional arguments or state ?
class R_Comp extends React.Component{
constructor(props, context) {
super(props, context)
};
;
55) What does a class component look like when written in TypeScript ?
[[ link to typescript ]]
56) How do you Change the State in a class component ?
The [[setState]] method can be used to change the state.
57) How can you handle asynchronous state updates ?
this.props and this.state may be updated at the same time.
To handle this you can pass a function into setState instead of just an object.
this.setState( function(prevState, prevProps) {
return (
counter: preState.counter + prevProps.increment
)};
);
Another alternative is to use an Arrow Function
this.setState( (prevState, prevProps) => ({
counter: preState.counter + prevProps.increment
});
);
58) Can you describe the Lifecycle for a class component ?
Every component has a lifecycle which you can monitor and manipulate during three main phases.
Mounting - adding elements into the DOM
(render)(constructor, getDerivedStateFromProps, componentDidMount)
Updating - a component is updated when there is a change to the state or props
(render)(getDerivedStateFromProps, shouldComponentUpdate, getSnapshotBeforeUpdate, componentDidUpdate)
UnMounting - removing elements from the DOM
(componentWillUnmount)
[[List all lifecycle methods]]
59) What will happen with respect to the shouldComponentUpdate lifecycle method as implemented in the following React component ?
This component will never update.
class R_Comp extends React.Component {
constructor(props) {
super(props);
this.state = {
key: 'value'
};
};
shouldComponentUpdate() {
return false;
};
render() {
return (
<div></div>
);
};
};
60) How would you delay an API call until a class component has mounted ?
In a class component you could use the componentDidMount lifecycle method
This code runs after the component has mounted.
61) How do you create a Form using a Controlled Component ?
In HTML form elements such as <input>, <textarea> and <select> usually maintain their own state and update it based on the user input.
In React we need to control the state using setState and we can do this by creating a controlled component.
This can be tedious though because you need to write an event handler for every way the data can change and pipe all the state through the component.
class R_Comp extends React.Component {
constructor(props) {
super(props);
this.state = {value:""}
this.m_handleSubmit = this.m_handleSubmit.bind(this);
};
m_handleChange(event) {
this.setState( {value:event.target.value} )
);
m_handleSubmit(event) {
alert('name entered : ' + this.state.value);
};
return (
<form onSubmit = {this.m_handleSubmit} >
<label>Name :</label>
<input type = "text"
value = {this.state.value}
onChange = {this.m_handleChange.bind(this)}
/>
<input type="submit" value='Submit'/>
</form>
);
};
62) How do you create a Form using an Uncontrolled Component ?
<input type = "text"
ref = { input => this.inputText = input }/>
63) What is a Pure / Stateless Component ?
It is a component that will always render the same output when provided with the same props and state.
A component that takes props and renders something based on the props.
A pure class component is a javascript class that extends React.PureComponent.
In function components, you can achieve these pure components through memoized React.memo() API wrapping around the component.
This API prevents unnecessary re-renders by comparing the previous props and new props using shallow comparison.
So it will be helpful for performance optimizations.
give a simple example
64) What is a Higher Order Component ?
This is a function that takes a component as an argument and returns a new component that wraps the original component.
A function that returns a function is a higher order function.
These act as containers for other components.
They are used when multiple components need to be reused.
They allow you to reuse component logic across multiple components.
A HOC is a pure function with zero side-effects.
65) What is the difference between Controlled and UnControlled components ?
Controlled components have their state managed by a parent component and passed down
These are easier to debug and considered best practice.
Easier to implement and add error handling
Controlled components use callbacks to notify the parent of any changes.
They rely on props passed down from the parent component.
UnControlled components manage their own state internally and use ref to update the DOM element directly.
66) Can you think of any situations when having a uncontrolled component might be necessary ?
manage focus
selecting text
media playback
67) What is a forwardRef ?
Lets your component expose a DOM node as a ref to the parent. Used with useRef.
68) What is React.lazy ?
Lets you defer loading a component's code until it's rendered for the first time.
Only works with client side rendering. Code splitting
Allows you to lazily load different modules at run-time.
Improves performance by dynamically importing only the component you need at runtime.
const R_OldRenderer = React.lazy( () => import('./R_OldRenderer.js') );
const R_NewRenderer = React.lazy( () => import('./R_NewRenderer.js') );
const R_Comp = (props) => {
if (FeatureFlag.useNewRenderer) {
return <R_NewRenderer {...props}/>;
} else {
return <R_OldRenderer {...props}/>;
}
}
69) What is Props Drilling ?
This is the process of passing down data through multiple layers of the component hierarchy.
An alternative to prop drilling is to use a state management library, such as Redux or the built-in Context API.
The term global state refers to having a global object that can be accessed by any component in the application.
70) What is the Context API ?
If you don't want to use a full fledged state management library (like Redux), you could use the Context API.
It works with both Functional and Class components.
React.createContext
context
this.context
(?i).*context.*Regular expression
71) What is Redux ?
Created by Facebooks and originally called Flux was a library / pattern that enforces one direction data flow.
It is a state management library that provides a centralized store for managing global application state.
Redux can be divided into 4 parts: Action, Reducer, Store, View
link - dev.to/codeofrelevancy/what-is-prop-drilling-in-react-3kol
Redux can be used with both Functional and Class components
(useSelector, useDispatch are used in functional components)
(connect is used in class components)
npm install react-redux
72) What is Routing ?
This is the mapping of different URLs to destinations that are not physical pages but are individual views in a single page application.
nested roues, dynamic routes
<Router>
73) What is the React Router API ?
This is a library that resolves the 'broken back button' problem and uses the History API.
74) What is React Native ?
React is completely independent from the browser.
React DOM is used when running in a browser.
React Native is used when running on mobile devices.
75) What is the React Developer Tools browser extension ?
This is a browser extension available for Edge, Chrome and Firefox that will add two new tabs to your DevTools pane (Components and Profiler).
These extra tabs can help you to inspect components, edit props and state and help identify performance problems.
76) What is Jest ?
npm install jest
Jest is a JavaScript Testing Framework created by Facebook in 2011.
It is a test runner that can be used for creating, finding, running tests and the determining if they have passed or failed.
Tests fall into three categories:
Unit Testing , Integration Testing , UI Testing
77) What is Mocking ?
This is a process used in unit testing when the unit being tested has external dependencies.
78) What is the React Testing Library ?
npm install @testing-library/react
This library replaces Enzyme and is built on top of the DOM Testing library.
This library provides helpers for rendering a React app, interacting with elements and being able to observe and check its appearance.
This library can be plugged into a test runner to allow it to perform UI testing.
79) How can you Test React Components ?
React components (functional and class) can be tested using a combination of Jest and the React Testing Library.
When you are writing tests you often need to check that values meet certain criteria.
In Jest the "expect" function will give you access to a number of different ways you can test the code.
The following matches can all be used with general JavaScript code (toBe, toBeTruthy, toContain)
When you want to test a React component you need to test the state of the DOM.
There is a dedicated Jest extension library that you can use with React to do this.
npm install @testing-library/jest-dom
80) What is 'react-hot-loader' ?
This is a webpack plugin that allows react components to be live reloaded.
81) What is GraphQL ?
Created by Facebook and designed as a query language for APIs
This is designed to replace Redux.
It supports web sockets
82) What is HTTP Streaming ?
You don't have to wait for all the data to be fetched before we start rendering
83) What is Selective Hydration ?
84) What are Styled Components ?
Styled components are components that include regular CSS inside them instead of referring to a separate file.
This method has become known as "CSS-In-JS".
CSS-In-JS is the sucessor to CSS Modules.
85) What is Inline Templating ?
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext