REACT js

https://www.simplilearn.com/tutorials/reactjs-tutorial/reactjs-interview-questions

https://www.interviewbit.com/react-interview-questions/#different-ways-to-style-react-component

usecontext

UseRef use cases

useRef returns a “ref” object. Values are accessed from the .current property of the returned object. The .current property could be initialized to an initial value — useRef(initialValue), for example. The object is persisted for the entire lifetime of the component.

One of the main use cases of using the hook useRef is to reference DOM elements in React. Every element in the DOM has an attribute called ref which we can set our ref to. Here is an example that allows us to access an input element and focus on it after clicking a button:

1. useRef

In React, the useRef hook is used to create a mutable reference that can persist across re-renders.




The useRef hook takes an initial value as an argument and returns a mutable ref object with a current property. 


The current property can be set and accessed directly, without triggering a re-render of the component. This is useful for storing a value or a reference to a DOM element that needs to be accessed later.


Here's an example of how to use useRef to store a reference to an input element and focus it when a button is clicked:

const Mycomponent = () => {
  const inputRef = useRef(null);
  const inputFocus = () => {
    inputRef.current.focus();
  };
  return (
    <>
      <input ref={inputRef} />
      <button onClick={inputFocus}>Focus on the Input</button>
    </>
  );
};

Another use case of useRef is for the storage that is persisted across component renders. The hook useRef allows us to store the previous value of a state. You can learn more about that if you're interested.

useState VS useRef

For useState:

  • Allows functional components to have their own state.
  • Allows us to update the state inside components.
  • It causes components to re-render after state updates.
  • Returns the current state.
  • Has an updater function that updates the state.

For useRef:

  • Returns an object with a property containing the initial value.
  • Doesn't cause a component to re-render when the value or state changes.
  • Data is persisted between renders.
  • Allows referencing DOM elements.

So these are the differences between these two extremely useful React hooks.

Conclusion

As you can see, both the hooks useState and useRef are a bit similar. The difference is that useState returns the current state and has an updater function that updates the state. While useRef returns an object, doesn't cause components to re-render, and it's used to reference DOM elements.





What is React?

React is a front-end and open-source JavaScript library which is useful in developing user interfaces specifically for applications with a single page. It is helpful in building complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.

The important features of React are:

  • It supports server-side rendering.
  • It will make use of the virtual DOM rather than real DOM (Data Object Model) as RealDOM manipulations are expensive.
  • It follows unidirectional data binding or data flow.
  • It uses reusable or composable UI components for developing the view.

What are the advantages of using React?

MVC is generally abbreviated as Model View Controller.

  • Use of Virtual DOM to improve efficiency: React uses virtual DOM to render the view. As the name suggests, virtual DOM is a virtual representation of the real DOM. Each time the data changes in a react app, a new virtual DOM gets created. Creating a virtual DOM is much faster than rendering the UI inside the browser. Therefore, with the use of virtual DOM, the efficiency of the app improves.
  • Gentle learning curve: React has a gentle learning curve when compared to frameworks like Angular. Anyone with little knowledge of javascript can start building web applications using React.
  • SEO friendly: React allows developers to develop engaging user interfaces that can be easily navigated in various search engines. It also allows server-side rendering, which boosts the SEO of an app.
  • Reusable components: React uses component-based architecture for developing applications. Components are independent and reusable bits of code. These components can be shared across various applications having similar functionality. The re-use of components increases the pace of development.
  • Huge ecosystem of libraries to choose from: React provides you with the freedom to choose the tools, libraries, and architecture for developing an application based on your requirement.

What are the major features of React?

The major features of React are:

  • Uses JSX syntax, a syntax extension of JS that allows developers to write HTML in their JS code.
  • It uses Virtual DOM instead of Real DOM considering that Real DOM manipulations are expensive.
  • Supports server-side rendering which is useful for Search Engine Optimizations(SEO).
  • Follows Unidirectional or one-way data flow or data binding.
  • Uses reusable/composable UI components to develop the view.

What is JSX ?

JSX stands for JavaScript XML. It allows us to write HTML inside JavaScript. It converts HTML tags into React Elements.

or

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React. 


Why JSX is required?

If you remember in the last post we creates our Hello World App using create-react-app. The code inside App.js file looks like this.

import React from "react"; 


function App() {
    /////////////////////////////
    return (
        <div>
            <h1>Hello World!</h1>
        </div>

    ); 
    //////////////////////////////
}

export default App; 

So what is you don't want to use JSX. Let's see how can we do that?

import React from "react"; 

function App() {
    /////////////////////////////
    return (
        React.createElement('div', null, 
        React.createElement(
            'h1', null, `Hello World!`
        ))

    ); 
    //////////////////////////////
}

export default App; 

This is the same code written without JSX. So, JSX allows us to write HTML elements in JavaScript without using any createElement() or appendChild() methods.

You are not required to use JSX, but JSX makes it easier to write React applications. Each JSX element is just syntactic sugar for calling React.createElement.
So, anything you can do with JSX can also be done with just plain JavaScript.


Rules for coding JSX

While writing JSX code you should keep the following things in mind.

  • Inserting JavaScript expressions. Any valid JavaScript expression can be inserted in JSX code by using the curly braces {}.
import React from "react"; 


function App() {
    return (
        <div>
            <h1>The sum of 6 and 9 is {6+9}</h1>
        </div>

    ); 
}

export default App; 
  • Top level Element All HTML code inside JSX must be wrapped in ONE top level element. So while writing multiple elements, you must put them inside one single parent element.
// WRONG WAY

function App() { 
 return (
   <h1>Hey, React!</h1>
   <h1>I love JSX!</h1>
 ); 
}
// CORRECT WAY

function App() { 
 return (
  <div>
    <h1>Hey, React!</h1>
    <h1>I love JSX!</h1>
  </div>
 ); 
}
  • A block of HTML code To write chunks of HTML on multiple lines, put the HTML inside parentheses and store it in a variable. This variable can be used anywhere in place of HTML.
const myelem = (
    <div>
        <h1>Hello React!</h1>
        <p>I love JSX!</p>
        <p>This is a block of code. </p>
    </div>
); 

function App() {
    return myelem; 
}
  • All elements must be closed All HTML elements must be properly closed. JSX will throw an error if HTML is not properly closed, it misses a parent element of incorrect in any other way.
const myelem = (
    <div>
        <img src="img.png" alt="Yay" />
        <input type="text" />
        <br/>
    </div>
); 

function App() {
    return myelem; 
}

// NOTICE THAT EVEN SELF CLOSING TAGS ARE PROPERLY CLOSED

What is the difference between Element and Component?

An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it cannot be mutated.

The JavaScript representation(Without JSX) of React Element would be as follows:

const element = React.createElement("div", { id: "login-btn" }, "Login");

and this element can be simiplified using JSX

  <div id="login-btn">Login</div>

The above React.createElement() function returns an object as below:

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

Finally, this element renders to the DOM using ReactDOM.render().

Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:

const Button = ({ handleLogin }) => (
  <div id={"login-btn"} onClick={handleLogin}>
    Login
  </div>
);

Then JSX gets transpiled to a React.createElement() function tree:

const Button = ({ handleLogin }) =>
  React.createElement(
    "div",
    { id: "login-btn", onClick: handleLogin },
    "Login"
  );

How to create components in React?

Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.

  1. Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the first parameter and return React elements to render the output:

    function Greeting({ message }) {
      return <h1>{`Hello, ${message}`}</h1>;
    }
  2. Class Components: You can also use ES6 class to define a component. The above function component can be written as a class component:

    class Greeting extends React.Component {
      render() {
        return <h1>{`Hello, ${this.props.message}`}</h1>;
      }

What is the difference between a functional component and a class component in React?

In React, a functional component is a plain JavaScript function that takes in props and returns a React element. A class component is a JavaScript class that extends React.Component and has a render method that returns a React element.

One key difference between the two is that a class component can have local state and lifecycle methods, while a functional component cannot. However, starting with React 16.8, functional components can also have a state using hooks.

Functional components are considered simpler, easier to understand and test, and have better performance than class components. Class components are useful when you need to use lifecycle methods or the local state.


What are Pure Components?

React pure components are the components that do not re-render when the value of props and state has been updated with the same values. Since these components do not cause re-rendering when the same values are passed thus they improve performance.

What is Pure Functions?

In Javascript, when functions returns same output when same input is passed is called Pure functions. It is like returning same data for same input. So in pure function output only depend on its input arguments. Pure functions does not produced any side effects as well. In past you may have already created so many pure function.
For example:

function Add(num1, num2){
  return num1 + num2;
}

If we call the above Add(2,2) function it will always return 4 as output. So if you call the above function with same input parameters multiple number of time it will always returns 4 output. Due to this pure function can optimize and improve the performance of function.

Pure functions in React

We know that in React we can create a component in two different ways i.e one is Class component/ Stateful component and another is Functional component/Stateless component. A React component can be considered pure if it renders the same output for the same state and props.

We can convert component to pure component as below:

  • For class components react provides React.PureComponent base class.
  • For Functional component react provides React.memo HOC (Higher Order Component).

React.PureComponent

When a class component extends React.PureComponent base class then React treated the component as Pure component. The major difference between React.Component class and React.PureComponent is the implementation of shouldComponentUpdate(). In React.Component shouldComponentUpdate() will always returns true on the other hand in React.PureComponent it will compare the current state and props with new state and props.

As React.PureComponent implements shouldComponentUpdate() method for Pure component which will improve performance and optimize rendering. But the point here is that it is only doing the shallow comparison so if you have very complex nested object then it may give you false result.

So let's create simple class component as shown below:

import React, { Component } from "react";

class PureClassComponent extends Component {
  constructor() {
    super();
    this.state = {
      name: "React JS"
    };
  }

  changeName = () => {
    this.setState({ name: "React JS" });
  };

  render() {
    console.log("FirstComponent -- Render method called");
    return (
      <div>
        <p> Name is : {this.state.name} </p>
        <button onClick={this.changeName}>Change Name</button>
      </div>
    );
  }
}

export default PureClassComponent;

In the above component when we click on button then we are setting the same value to name in the state. But interesting thing is that even if we are setting same value it will always re-render the component.

pure-component

Here are the Pure components comes into picture. Pure component compare the current state with new state and current props to new props whenever the setState() method is called. So this will help to reduce the unnecessary calls to render() method.

Now just import PureComponent class from react library and extend current component with PureComponent class and see the output in console.

pure-component-1

Whenever we click on Change Name button we are assigning same value to state but it is not calling render method again and again.

React.memo

React.memo is nothing but a Higher Order function (HOC). React.memo is similar to React.PureComponent and it is for functional component instead of class component. You can wrap your functional component when component renders same output with same props passed. Due to this it will improve the performance and optimize the rendering.

React.memo only works when props of components changes. It means that if you are using state using useState hook in functional then for every state change it will render the component. Similar to React.PureComponent it is doing shallow comparison of props.

React.memo takes a first argument as component and returns a special kind of React component.

For demo purpose I have create simple counter app as shown below.

CustomLabel.js

import React from "react";

export default ({ name }) => {
  return (
    <>
      {console.log("CustomLabel component render")}
      <label>
        <b>{name}</b>
      </label>
    </>
  );
};

CounterComponent.js

import React, { useState } from "react";
import CustomLabel from "./CustomLabel";

const CounterComponent = () => {
  const [counter, setCounter] = useState(0);

  return (
    <div>
      <CustomLabel name="Simple Counter app" />
      <p>Counter is : {counter} </p>
      <button onClick={() => setCounter(counter + 1)}>Click</button>
    </div>
  );
};
export default CounterComponent;

memo

Here I have created two components i.e CounterComponent and CustomLabel component. CustomLabel component accepts name as prop and display it in label tag. In CustomLabel component, we have added console.log() so that we can see how many times the component is getting render. Whenever you click on button to increase count it will re-render CustomLabel Component.

Now the 'React.memo' comes in picture. So wrap the CustomLabel component inside the 'React.memo' HOC and test the application again. You will see it renders the CustomLabel component only once because the name prop is remains same on every button click.

CustomLabel.js

import React, {memo} from "react";

const CustomLabel=({ name }) => {
  return (
    <>
      {console.log("CustomLabel component render")}
      <label>
        <b>{name}</b>
      </label>
    </>
  );
};
export default memo(CustomLabel);

memo-1

Conclusion

In this article, I have explained about Pure components in React JS and also discussed how to convert Class and Functional component into Pure components.

I really hope that you enjoyed this article, share it with friends and please do not hesitate to send me your thoughts or comments.


What Is ‘State’ in ReactJS?

The state is a built-in React object that is used to contain data or information about the component. A component’s state can change over time; whenever it changes, the component re-renders. The change in state can happen as a response to user action or system-generated events and these changes determine the behavior of the component and how it will render.  

class Greetings extends React.Component {

  state = {

    name: "World"

  };

  updateName() {

    this.setState({ name: "Simplilearn" });

  }

  render() {

      return(

          <div>

              {this.state.name}

          </div>

      )

  }

}

  • A state can be modified based on user action or network changes
  • Every time the state of an object changes, React re-renders the component to the browser
  • The state object is initialized in the constructor
  • The state object can store multiple properties
  • this.setState() is used to change the value of the state object
  • setState() function performs a shallow merge between the new and the previous state


kkkkkkkkk

What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

What is the difference between State and props in ReactJs?

State - This is data maintained inside a component. It is local or owned by that specific component. The component itself will update the state using the setState function.

Props - Data passed in from a parent component. props are read-only in the child component that receives them. However, callback functions can also be passed, which can be executed inside the child to initiate an update.

The difference is all about which component owns the data. State is owned locally and updated by the component itself. Props are owned by a parent component and are read-only. Props can only be updated if a callback function is passed to the child to trigger an upstream change.

The state of a parent component can be passed a prop to the child. They are referencing the same value, but only the parent component can update it.



Why should we not update the state directly?

If you try to update the state directly then it won't re-render the component.

//Wrong
this.state.message = "Hello world";

Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.

//Correct
this.setState({ message: "Hello World" });

Note: You can directly assign to the state object either in constructor or using latest javascript's class field declaration syntax.

What are inline conditional expressions?

You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.

<h1>Hello!</h1>;
{
  messages.length > 0 && !isLogin ? (
    <h2>You have {messages.length} unread messages.</h2>
  ) : (
    <h2>You don't have unread messages.</h2>
  );
}
  1. What is the use of refs?

    The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.

     Back to Top

  2. How to create refs?

    There are two approaches

    1. This is a recently added approach. Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property within constructor.

      class MyComponent extends React.Component {
        constructor(props) {
          super(props);
          this.myRef = React.createRef();
        }
        render() {
          return <div ref={this.myRef} />;
        }
      }
    2. You can also use ref callbacks approach regardless of React version. For example, the search bar component's input element is accessed as follows,

      class SearchBar extends Component {
        constructor(props) {
          super(props);
          this.txtSearch = null;
          this.state = { term: "" };
          this.setInputSearchRef = (e) => {
            this.txtSearch = e;
          };
        }
        onInputChange(event) {
          this.setState({ term: this.txtSearch.value });
        }
        render() {
          return (
            <input
              value={this.state.term}
              onChange={this.onInputChange.bind(this)}
              ref={this.setInputSearchRef}
            />
          );
        }
      }

    You can also use refs in function components using closuresNote: You can also use inline ref callbacks even though it is not a recommended approach.

  1. What are the different phases of component lifecycle?

    The component lifecycle has three distinct lifecycle phases:

    1. Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor()getDerivedStateFromProps()render(), and componentDidMount() lifecycle methods.

    2. Updating: In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.

    3. Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.  All the cleanups such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() should be coded in the componentWillUnmount() method block.

    It's worth mentioning that React internally has a concept of phases when applying changes to the DOM. They are separated as follows

    1. Render The component will render without any side effects. This applies to Pure components and in this phase, React can pause, abort, or restart the render.

    2. Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate().

    3. Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.

    React 16.3+ Phases (or an interactive version)

    phases 16.4+

    Before React 16.3

    phases 16.2

     Back to Top

  2. What are the lifecycle methods of React?

    Before React 16.3

    • componentWillMount: Executed before rendering and is used for App level configuration in your root component.
    • componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.
    • componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.
    • shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.
    • componentWillUpdate: Executed before re-rendering the component when there are props & state changes confirmed by shouldComponentUpdate() which returns true.
    • componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes.
    • componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

    React 16.3+

    • getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need a derived state. Worth reading if you need derived state.
    • componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners should occur.
    • shouldComponentUpdate: Determines if the component will be updated or not. By default, it returns true. If you are sure that the component doesn't need to render after the state or props are updated, you can return a false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives a new prop.
    • getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by this will be passed into componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.
    • componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if shouldComponentUpdate() returns false.
    • componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

 

What are Higher-Order Components?

Higher order components are JavaScript functions used for adding additional functionalities to the existing component. These functions are pure, which means they are receiving data and returning values according to that data. If the data changes, higher order functions are re-run with different data input. If we want to update our returning component, we don't have to change the HOC. All we need to do is change the data that our function is using.

Higher Order Component (HOC) is wrapping around "normal" component and provide additional data input. It is actually a function that takes one component and returns another component that wraps the original one.

A Higher Order Component (HOC) is a technique in React that enables code reuse.

It is a function that takes an existing component as an argument(input) and returns a new component.

This new component "wraps" the original component and can add extra features, such as props or state, to the wrapped component.

Let's take an example,

function higherOrderComponent(WrappedComponent) {
    return (props) => {
        return <WrappedComponent {...props} />;
    }
}

const Component = (props) => {
    return (<h1>Hello {props.name}!</h1>)
};

const NewComponent = higherOrderComponent(Component);

const element = <NewComponent name="React" />;
  1. What are stateless components?

    If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.

     Back to Top

  2. What are stateful components?

    If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are either function components with hooks or class components.

    Let's take an example of function stateful component which update the state based on click event,

    import React, {useState} from 'react';
    
    const App = (props) => {
    const [count, setCount] = useState(0);
    handleIncrement() {
      setCount(count+1);
    }
    
    return (
      <>
        <button onClick={handleIncrement}>Increment</button>
        <span>Counter: {count}</span>
      </>
      )
    }

How do you conditionally render components?

In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address && <p>{address}</p>}
  </div>
);

If you need an if-else condition then use ternary operator.

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address ? <p>{address}</p> : <p>{"Address is not available"}</p>}
  </div>
);


What is the purpose of render() in React.

Each React component must have a render() mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div> etc. This function must be kept pure i.e., it must return the same result each time it is invoked.


 How can you update the state of a component?

State of a component can be updated using this.setState().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (                                
 
<div>
                   
<h1>Hello {this.state.name}</h1>
     
<h2>Your Id is {this.state.id}</h2>
 
                   </div>
 
            );
        }
    }
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')

llllllllllllllllllllllllllll

Differentiate between stateful and stateless components.

Stateful vs Stateless


Stateful ComponentStateless Component
1. Stores info about component’s state change in memory1. Calculates the internal state of the components
2. Have authority to change state2. Do not have the authority to change state
3. Contains the knowledge of past, current and possible future changes in state3. Contains no knowledge of past, current and possible future state changes
4. Stateless components notify them about the requirement of the state change, then they send down the props to them.4. They receive the props from the Stateful components and treat them as callback functions.
  1. What is flux?

    Flux is an application design paradigm used as a replacement for the more traditional MVC pattern. It is not a framework or a library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow. Facebook uses this pattern internally when working with React.

    The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:

    flux

 Back to Top

  1. What is Redux?

    Redux is a predictable state container for JavaScript apps based on the Flux design pattern. Redux can be used together with React, or with any other view library. It is tiny (about 2kB) and has no dependencies.

  1. What are the core principles of Redux?

    Redux follows three fundamental principles:

    1. Single source of truth: The state of your whole application is stored in an object tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
    2. State is read-only: The only way to change the state is to emit an action, an object describing what happened. This ensures that neither the views nor the network callbacks will ever write directly to the state.
    3. Changes are made with pure functions: To specify how the state tree is transformed by actions, you write reducers. Reducers are just pure functions that take the previous state and an action as parameters, and return the next state.
    4. What do you understand by “Single source of truth”?

      Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

      39. List down the components of Redux.

      Redux is composed of the following components:

      1. Action – It’s an object that describes what happened.
      2. Reducer –  It is a place to determine how the state will change.
      3. Store – State/ Object tree of the entire application is saved in the Store.
      4. View – Simply displays the data provided by the Store.

      In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

  2. Preventing re-renders with React.memo
    Wrapping a component in React.memo will stop the downstream chain of re-renders that is triggered somewhere up the render tree, unless this component's props have changed.
  3. Reason for re-renders in React:
    • Re-rendering of a component and its child components occur when props or the state of the component has been changed.
    • Re-rendering components that are not updated, affects the performance of an application.
  4.  What are the different ways to style a React component?

    There are many different ways through which one can style a React component. Some of the ways are :

    • Inline Styling: We can directly style an element using inline style attributes. Make sure the value of style is a JavaScript object:
    class RandomComponent extends React.Component {
     render() {
       return (
         <div>
           <h3 style={{ color: "Yellow" }}>This is a heading</h3>
           <p style={{ fontSize: "32px" }}>This is a paragraph</p>
         </div>
       );
     }
    }
    • Using JavaScript object: We can create a separate JavaScript object and set the desired style properties. This object can be used as the value of the inline style attribute.
    class RandomComponent extends React.Component {
     paragraphStyles = {
       color: "Red",
       fontSize: "32px"
     };
    
     headingStyles = {
       color: "blue",
       fontSize: "48px"
     };
    
     render() {
       return (
         <div>
           <h3 style={this.headingStyles}>This is a heading</h3>
           <p style={this.paragraphStyles}>This is a paragraph</p>
         </div>
       );
     }
    }
    • CSS Stylesheet: We can create a separate CSS file and write all the styles for the component inside that file. This file needs to be imported inside the component file.
    import './RandomComponent.css';
    
    class RandomComponent extends React.Component {
     render() {
       return (
         <div>
           <h3 className="heading">This is a heading</h3>
           <p className="paragraph">This is a paragraph</p>
         </div>
       );
     }
    }
    • CSS Modules: We can create a separate CSS module and import this module inside our component. Create a file with “.module.css”‘ extension, styles.module.css:
    .paragraph{
     color:"red";
     border:1px solid black;
    }

    We can import this file inside the component and use it:

    import styles from  './styles.module.css';
    
    class RandomComponent extends React.Component {
     render() {
       return (
         <div>
           <h3 className="heading">This is a heading</h3>
           <p className={styles.paragraph} >This is a paragraph</p>
         </div>
       );
     }
    }
oooooooooooooooooooooooooo

Name a few techniques to optimize React app performance.

There are many ways through which one can optimize the performance of a React app, let’s have a look at some of them:

  • Using useMemo( ) -
    • It is a React hook that is used for caching CPU-Expensive functions.
    • Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.
      useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed.
  • Using React.PureComponent -
    • It is a base component class that checks the state and props of a component to know whether the component should be updated.
    • Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily.
  • Maintaining State Colocation -
    • This is a process of moving the state as close to where you need it as possible.
    • Sometimes in React app, we have a lot of unnecessary states inside the parent component which makes the code less readable and harder to maintain. Not to forget, having many states inside a single component leads to unnecessary re-renders for the component.
    • It is better to shift states which are less valuable to the parent component, to a separate component.
  • Lazy Loading -
    •  It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to a minimum
    •  Provide > Use

      Now we will learn step by step to use and create useContext :

      Step 1 (Create)

      Always prefer to create a separate Context.js file in the src folder to use the useContext.
      As told in the above flow, our first step would be to create the useContext hook. In the following snippet, we will import the different hooks and function to create the context. We use createContext function to create the context.

      // Context.js
      
      import React, { useState, createContext, useContext } from "react";
      
      const CounterContext = createContext();
      
      

      Step 2 (Provide)

      Now we will use the above CounterContext and wrap our whole application to provide the values to every component.

      // Context.js
      
      export const NameContextProvider = ({ children }) => {
        const [counter, setCounter] = useState(0);
        return (
          <CounterContext.Provider value={{ counter, setCounter }}>
            {children}
          </CounterContext.Provider>
        );
      };
      
      
      // index.js
      
      import { NameContextProvider } from "./Context";
      import App from "./App";
      
      const rootElement = document.getElementById("root");
      ReactDOM.render(
          <NameContextProvider>
            <App />
          </NameContextProvider>,
        rootElement
      );
      
      
      

      Because we wrapped our application in the index.js file using the NameContextProviderchildren will be our application in the above snippet. To build the state, we're using a simple useState hook. The component Provider in the CounterContext.Provider></CounterContext.Provider> helps the context deliver state values to all the components that have been wrapped around. The value of all the states and functions that we want to share with components is referred to as value In the value field, we can put anything we want.

      Step 3 (Use)

      Now the last step is using the context we have created using the useContext hook.

      export const UseCounterContext = () => useContext(CounterContext);
      
      

      Note: Always remember to export the UseCounterContext and NameContextProvider.

      These were the steps for creating the context.

      • Now all we have to do is create the various components and use this state value to update the state value as needed. We'll make three separate components: one to increase the value, one to decrease the value, and one to reset the state's value to zero. I will show only one component in the following snippet all other components will follow the same method with some changes in the state updating function setCounter.
      // Increase.js
      
      import { UseCounterContext } from "./Context";
      
      const Increase = () => {
      
        const { counter, setCounter } = UseCounterContext();
      
        const increaseHandler = () => {
          setCounter((prevValue) => prevValue + 1);
        };
      
        return (
          <div className="component">
            <h3>I am counter {counter} in ComponentA</h3>
            <button onClick={increaseHandler}>Increase</button>
          </div>
        );
      };
      
      export default Increase;
      
      
      

      To utilize the value of the context we have to import the UseCounterContext which we created in Step 3 (Use) of the context. After importing the UseCounterContext we will destructure all the values passed in values in the Context.js file. Since we passed the counter and setCounter and we need only these values in our component so we will destructure these values and use them in the component.

      Note: We can destructure only those values that we are going to use in the particular component.
      Since the above snippet is for Increase.js component we will increase the value of the counter using the setCounter function.

      Create the Decrease.js and Reset.js functions similarly.
      Here is the final codesandbox.


      What are inline conditional expressions?

      You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator 

what are controlled and uncontrolled components in react ?

In React, controlled components they have their state and behavior controlled by the parent component. These components rely on props passed down from the parent component to update their state and behavior. Uncontrolled components refer to components that manage their own state internally. They use a ref to access the DOM element's current value and update the state accordingly.

What Are Controlled Components in React?
A component in react is referred to as controlled when we let react control the component for us. It means that the component controls the input form, and all of its changes are completely driven by event handlers like setState(). Also, the component controls the render and keeps the data of form in the component state.

What Are Uncontrolled Components in React?
After studying the controlled components, it must be clear that the uncontrolled component react does not use state. Thus uncontrolled components do not depend on any state of input elements or any event handler. This type of component does not care about real-time input changes.

  • It is a must to use react state in a controlled component to handle the dynamic form data. It is optional for the uncontrolled component to have a state, but it must use react Ref.

Comments