React 4of4 Flashcards

1
Q

<p>Is it recommended to use CSS In JS technique in React?</p>

A

<p>React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate *.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries. But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

<p>Do I need to rewrite all my class components with hooks?</p>

A

<p>No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

<p>How to fetch data with React Hooks?</p>

A

<p>The effect hook called useEffect is used to fetch the data with axios from the API and to set the data in the local state of the component with the state hook’s update function.
<br></br>
<br></br>Let's take an example in which it fetches list of react articles from the API
<br></br>
<br></br>import React, { useState, useEffect } from 'react';
<br></br>import axios from 'axios';
<br></br>
<br></br>function App() {
<br></br> const [data, setData] = useState({ hits: [] });
<br></br>
<br></br> useEffect(() => {
<br></br> (async () => {
<br></br> const result = await axios(
<br></br> 'http://hn.algolia.com/api/v1/search?query=react',
<br></br> );
<br></br>
<br></br> setData(result.data);
<br></br> })()
<br></br> }, []);
<br></br>
<br></br> return (
<br></br> </p>

<ul>
<br></br> {data.hits.map(item => (
<br></br> <li>
<br></br> <a>{item.title}</a>
<br></br> </li>
<br></br> ))}
<br></br> </ul>

<br></br> );
<br></br>}
<br></br>
<br></br>export default App;
<br></br>
<br></br>Remember we provided an empty array as second argument to the effect hook to avoid activating it on component updates but only on mounting of the component. i.e, It fetches only on component mount.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

<p>Is Hooks cover all use cases for classes?</p>

A

<p>Hooks doesn't cover all use cases of classes but there is a plan to add them soon. Currently there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

<p>What is the stable release for hooks support?</p>

A

<p>React includes a stable implementation of React Hooks in 16.8 release for below packages
<br></br>
<br></br>React DOM
<br></br>React DOM Server
<br></br>React Test Renderer
<br></br>React Shallow Renderer</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

<p>Why do we use array destructuring (square brackets notation) in useState?</p>

A

<p>When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.
<br></br>
<br></br>For example, the array index access would look as follows:
<br></br>
<br></br> var userStateVariable = useState('userProfile'); // Returns an array pair
<br></br> var user = userStateVariable[0]; // Access first item
<br></br> var setUser = userStateVariable[1]; // Access second item
<br></br>Whereas with array destructuring the variables can be accessed as follows:
<br></br>
<br></br>const [user, setUser] = useState('userProfile');</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

<p>What are the sources used for introducing hooks?</p>

A

<p>Hooks got the ideas from several different sources. Below are some of them,
<br></br>
<br></br>Previous experiments with functional APIs in the react-future repository
<br></br>Community experiments with render prop APIs such as Reactions Component
<br></br>State variables and state cells in DisplayScript.
<br></br>Subscriptions in Rx.
<br></br>Reducer components in ReasonReact.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

<p>How do you access imperative API of web components?</p>

A

<p>Web Components often expose an imperative API to implement its functions. You will need to use a ref to interact with the DOM node directly if you want to access imperative API of a web component. But if you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

<p>What is formik?</p>

A

<p>Formik is a small react form library that helps you with the three major problems,
<br></br>
<br></br>Getting values in and out of form state
<br></br>Validation and error messages
<br></br>Handling form submission</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

<p>What are typical middleware choices for handling asynchronous calls in Redux?</p>

A

<p>Some of the popular middleware choices for handling asynchronous calls in Redux eco system are Redux Thunk, Redux Promise, Redux Saga.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

<p>Do browsers understand JSX code?</p>

A

<p>No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

<p>Describe about data flow in react?</p>

A

<p>React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

<p>What is react scripts?</p>

A

<p>The react-scripts package is a set of scripts from the create-react-app starter pack which helps you kick off projects without configuring. The react-scripts start command sets up the development environment and starts a server, as well as hot module reloading.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

<p>What are the features of create react app?</p>

A

<p>Below are the list of some of the features provided by create react app.
<br></br>
<br></br>React, JSX, ES6, Typescript and Flow syntax support.
<br></br>Autoprefixed CSS
<br></br>CSS Reset/Normalize
<br></br>A live development server
<br></br>A fast interactive unit test runner with built-in support for coverage reporting
<br></br>A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps
<br></br>An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

<p>What is the purpose of renderToNodeStream method?</p>

A

<p>The ReactDOMServer#renderToNodeStream method is used to generate HTML on the server and send the markup down on the initial request for faster page loads. It also helps search engines to crawl your pages easily for SEO purposes. Note: Remember this method is not available in the browser but only server.</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

<p>What is MobX?</p>

A

<p>MobX is a simple, scalable and battle tested state management solution for applying functional reactive programming (TFRP). For reactJs application, you need to install below packages,
<br></br>npm install mobx --save
<br></br>npm install mobx-react --save</p>

17
Q

<p>What are the differences between Redux and MobX?</p>

A

<p>Below are the main differences between Redux and MobX,</p>

18
Q

Should I learn ES6 before learning ReactJS?

A

No, you don’t have to learn es2015/es6 to learn react. But you may find many resources or React ecosystem uses ES6 extensively. Let’s see some of the frequently used ES6 features,

[1] Destructuring: To get props and use them in a component
// in es 5
 var someData = this.props.someData
 var dispatch = this.props.dispatch
// in es6
const { someData, dispatch } = this.props
[2] Spread operator: Helps in passing props down into a component
// in es 5

// in es6

[3] Arrow functions: Makes compact syntax
// es 5
var users = usersList.map(function (user) {
 return <li>{user.name}</li>
})
// es 6
const users = usersList.map(user => <li>{user.name}</li>);
19
Q

What is Concurrent Rendering?

A

The Concurrent rendering makes React apps to be more responsive by rendering component trees without blocking the main UI thread. It allows React to interrupt a long-running render to handle a high-priority event. i.e, When you enabled concurrent Mode, React will keep an eye on other tasks that need to be done, and if there’s something with a higher priority it will pause what it is currently rendering and let the other task finish first. You can enable this in two ways,

// 1. Part of an app by wrapping with ConcurrentMode

// 2. Whole app using createRoot
ReactDOM.unstable_createRoot(domNode).render();
20
Q

What is the difference between async mode and concurrent mode?

A

Both refers the same thing. Previously concurrent Mode being referred to as “Async Mode” by React team. The name has been changed to highlight React’s ability to perform work on different priority levels. So it avoids the confusion from other approaches to Async Rendering.

21
Q

Can I use javascript urls in react16.9?

A

Yes, you can use javascript: URLs but it will log a warning in the console. Because URLs starting with javascript: are dangerous by including unsanitized output in a tag like <a> and create a security hole.</a>

const companyProfile = {
website: “javascript: alert(‘Your website is hacked’)”,
};
// It will log a warning
</a><a>More details</a>
Remember that the future versions will throw an error for javascript URLs.

22
Q

What is the purpose of eslint plugin for hooks?

A

The ESLint plugin enforces rules of Hooks to avoid bugs. It assumes that any function starting with ”use” and a capital letter right after it is a Hook. In particular, the rule enforces that,

Calls to Hooks are either inside a PascalCase function (assumed to be a component) or another useSomething function (assumed to be a custom Hook).
Hooks are called in the same order on every render.

23
Q

What is the difference between Imperative and Declarative in React?

A

Imagine a simple UI component, such as a “Like” button. When you tap it, it turns blue if it was previously grey, and grey if it was previously blue.

The imperative way of doing this would be:

if( user.likes() ) {
    if( hasBlue() ) {
        removeBlue();
        addGrey();
    } else {
        removeGrey();
        addBlue();
    }
}
Basically, you have to check what is currently on the screen and handle all the changes necessary to redraw it with the current state, including undoing the changes from the previous state. You can imagine how complex this could be in a real-world scenario.

In contrast, the declarative approach would be:

if( this.state.liked ) {
    return ;
} else {
    return ;
}
Because the declarative approach separates concerns, this part of it only needs to handle how the UI should look in a sepecific state, and is therefore much simpler to understand.
24
Q

What are the benefits of using typescript with reactjs?

A

Below are some of the benefits of using typescript with Reactjs,

[1] It is possible to use latest JavaScript features
[2] Use of interfaces for complex type definitions
[3] IDEs such as VS Code was made for TypeScript
[4] Avoid bugs with the ease of readability and Validation

25
Q

How do you make sure that user remains authenticated on page refresh while using Context API State Management?

A

When a user logs in and reload, to persist the state generally we add the load user action in the useEffect hooks in the main App.js. While using Redux, loadUser action can be easily accessed.

App.js

import {loadUser} from ‘../actions/auth’;
store.dispatch(loadUser());
But while using Context API, to access context in App.js, wrap the AuthState in index.js so that App.js can access the auth context. Now whenever the page reloads, no matter what route you are on, the user will be authenticated as loadUser action will be triggered on each re-render.
index.js

import React from ‘react’;
import ReactDOM from ‘react-dom’;
import App from ‘./App’;
import AuthState from ‘./context/auth/AuthState’

ReactDOM.render(

,
document.getElementById(‘root’)
);
App.js

const authContext = useContext(AuthContext);

const { loadUser } = authContext;

useEffect(() => {
loadUser();
},[])
loadUser

    const loadUser = async () => {
        const token = sessionStorage.getItem('token');
        if(!token){
            dispatch({
                type: ERROR
            })
        }
        setAuthToken(token);
        try {
            const res = await axios('/api/auth'); 
        dispatch({
            type: USER_LOADED,
            payload: res.data.data
        })

    } catch (err) {
       console.error(err); 
    }
}
26
Q

What are the benefits of new JSX transform?

A

There are three major benefits of new JSX transform,

[1] It is possible to use JSX without importing React packages
[2] The compiled output might improve the bundle size in a small amount
[3] The future improvements provides the flexibility to reduce the number of concepts to learn React.

27
Q

How does new JSX transform different from old transform?

A

The new JSX transform doesn’t require React to be in scope. i.e, You don’t need to import React package for simple scenarios.

Let’s take an example to look at the main differences between the old and the new transform,

Old Transform:

import React from ‘react’;

function App() {
  return <h1>Good morning!!</h1>;
}
Now JSX transform convert the above code into regular JavaScript as below,

import React from ‘react’;

function App() {
  return React.createElement('h1', null, 'Good morning!!');
}
New Transform:

The new JSX transform doesn’t require any React imports

function App() {
  return <h1>Good morning!!</h1>;
}
Under the hood JSX transform compiles to below code

import {jsx as _jsx} from ‘react/jsx-runtime’;

function App() {
  return _jsx('h1', { children: 'Good morning!!' });
}
Note: You still need to import React to use Hooks.
28
Q

How do you get redux scaffolding using create-react-app?

A

Redux team has provided official redux+js or redux+typescript templates for create-react-app project. The generated project setup includes,

[1] Redux Toolkit and React-Redux dependencies
[2] Create and configure Redux store
[3] React-Redux passing the store to React components
[4] Small “counter” example to demo how to add redux logic and React-Redux hooks API to interact with the store from components

The below commands need to be executed along with template option as below,

[1] Javascript template:
npx create-react-app my-app –template redux

[2] Typescript template:
npx create-react-app my-app –template redux-typescript

29
Q

What are React Server components?

A

React Server Component is a way to write React component that gets rendered in the server-side with the purpose of improving React app performance. These components allow us to load components from the backend.

Note: React Server Components is still under development and not recommended for production yet.

30
Q

What is prop drilling?

A

Prop Drilling is the process by which you pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around.

31
Q

What is state mutation and how to prevent it?

A

State mutation happens when you try to update the state of a component without actually using setState function. This can happen when you are trying to do some computations using a state variable and unknowingly save the result in the same state variable. This is the main reason why it is advised to return new instances of state variables from the reducers by using Object.assign({}, …) or spread syntax.

This can cause unknown issues in the UI as the value of the state variable got updated without telling React to check what all components were being affected from this update and it can cause UI bugs.

Ex:

class A extends React.component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
 }

componentDidMount() {
let { loading } = this.state;
loading = (() => true)(); // Trying to perform an operation and directly saving in a state variable
}
How to prevent it: Make sure your state variables are immutable by either enforcing immutability by using plugins like Immutable.js, always using setState to make updates, and returning new instances in reducers when sending updated state values.

32
Q

What is the difference between useState and useRef hook?

A

[1] useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes. Essentially, useRef is like a “box” that can hold a mutable value in its (.current) property.

[2] useState allows us to update the state inside components. While useRef allows refrencing DOM elements.