Most important concepts of React.js

  1. What are the different ways to update the state with examples?

  2. What is the difference between client-side routing and server-side routing?

  3. Difference between class component & functional component.

  4. What are the different lifecycle methods in React?

  5. Can you pass data from children to parent components using props?

  6. How can you pass data from children to parents?


    What are the different ways to update the state with examples?

    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.
There are the ways to update the state in JavaScript, including using the setState() method, the useState() hook..
  • Using setState(): The setState() method is a built-in React method that is used to update the state of a component. It takes two arguments, the first being the new state and the second being a callback function executed once the state has been updated.

    Example:

    
      this.setState({
        count: this.state.count + 1
      }, () => {
        console.log(this.state.count);
      });
    
  • Using useState(): The useState() hook is a built-in React hook that is used to update the state of a functional component. It takes a single argument, which is the initial value of the state and returns an array containing the current state and a setter function for updating the state.

    Example:

      const [count, setCount] = useState(0);
      setCount(count + 1);
    

    The example of a counter app below will help you to understand:

      import React from "react";
      import "./App.css";
    
      class App extends React.Component {
          constructor(){
              super();
              this.state = {
                  counter : 0,
              }
          }
          IncEvent = () =>{
              this.setState((prevState) => {
                  return {
                      counter : prevState.counter + 1
                  }
              })
    
          }
          DecEvent = () =>{
              this.setState((prevState)=>{
                  return{
                   counter : prevState.counter > 0 ? prevState.counter -1 : 0
             }
              })
          }
          resEvent = () =>{
              this.setState({
                  counter : 0
              })
          }
          render(){
              return (
                  <center>
                  <h1>Counter App</h1>
                  <h2>{this.state.counter}</h2>
                  <button onClick={this.IncEvent} ><span>Increment </span></button>
                  <button onClick={this.DecEvent} ><span>Decrement </span></button>
                  <button onClick={this.resEvent} ><span>Reset</span></button>
                  </center>
              )
          }
      }
    
      export default App;
    

    What is the difference between client-side routing and server-side routing?

    • Every application in the world use Routing

    • When you click on any of the link it will take you to specific page based on what you clicked on.

      Routing is a fundamental part of any web application, as it is responsible for handling requests and directing them to the correct controller action.

    • Different application handle routing in different way.

      1. Server Side Routing

      2. Client Side Routing

**1) Server Side Routing:**
  • When you clicked on the link every time you or you change the URL based on that the browser will request to server and server will give them HTML, CSS, JS file and based on that page will visible this is called server side routing.

  • Server side route will only request the data that is needed. No more , No less.

  • Search engine are optimised for webpages that comes from the server.

  • Example: Wikipedia.com website

    An image illustrating server-side routing

    2) Client Side Routing:

  • It made the first request, you got your HTML and CSS file in the browser when you update the route it is not going to the server side it is directly going to HTML and CSS JS file and based on your route the routing will happens inside the browser only, that is know as is is client side routing.

  • Routing between pages are faster.

  • Transition and Animation is really smooth.

  • Example: reactjs.org website

    An image illustrating client-side routing

Difference between class component & functional component.

React.JS Components

  • Components are reusable bits of code.

  • They are same like JavaScript's functions.

  • Components name should be always start with Uppercase letter.

  • Components comes in two types, Class components and Function components.

When to use Class Component and Function Component?? - DEV Community  👩‍💻👨‍💻

Class ComponentsFunction Components
Class component is statefull.Function component is stateless.
We can use React lifecycle methods in Class component.We can't use React lifecycle methods in Function component.
It must have render method.There is no render method used in function component.
A class component requires you to extend from React. Component and create a render function which returns a React element.A functional component is just a plain JavaScript function that accepts props as an argument and returns a React element.
We can't use Hook inside Class component.We can use Hook in Function component for state management.
//Example of Class Component 
// This is Counter App Code in Class component
import React from "react";
import "./App.css";

class App extends React.Component {
    constructor(){
        super();
        this.state = {
            counter : 0,
        }
    }
    IncEvent = () =>{
        this.setState((prevState) => {
            return {
                counter : prevState.counter + 1
            }
        })

    }
    DecEvent = () =>{
        this.setState((prevState)=>{
            return{
             counter : prevState.counter > 0 ? prevState.counter -1 : 0
       }
        })
    }
    resEvent = () =>{
        this.setState({
            counter : 0
        })
    }
    render(){
        return (
            <center>
            <h1>Counter App</h1>
            <h2>{this.state.counter}</h2>
            <button onClick={this.IncEvent} ><span>Increment </span></button>
            <button onClick={this.DecEvent} ><span>Decrement </span></button>
            <button onClick={this.resEvent} ><span>Reset</span></button>
            </center>
        )
    }
}

export default App;
//Example of Functional Component 
function Heading() {
    return (
    <>
      <div className="Class">
        <h1>All Articles</h1>
        <h3>Collection of best articles on Startups</h3>
        </div>
    </>
    );
  }

A Guide to React Lifecycle Methods

"React is a powerful library for building user interfaces, and one of the features that makes it so powerful is the lifecycle methods. These methods allow developers to control how components are created, updated, and destroyed in a React application."

What are React Lifecycle Methods?

  • React lifecycle methods are special methods that are provided by the React library to help developers control the creation, updating, and destruction of components.

  • These methods are called at different stages of the component’s life cycle and can be used to do things such as set up state, fetch data, or update the UI.

  • The most commonly used lifecycle methods are componentDidMount, componentDidUpdate, and componentWillUnmount.

    LifeCycle

componentDidMount()

  • The componentDidMount lifecycle method is called after a component has been mounted to the DOM.

  • This is the perfect place to do any setup that needs to be done after a component is created, such as setting up state or fetching data.

componentDidUpdate()

  • The componentDidUpdate lifecycle method is called after a component has been updated.

  • This is the perfect place to do any cleanup or data fetching that needs to happen after a component has been updated.

componentWillUnmount()

  • The componentWillUnmount lifecycle method is called before a component is unmounted and destroyed.

  • This is the perfect place to do any cleanup that needs to be done before the component is destroyed, such as clearing timers or cleaning up event listeners.

Can you pass data from children to parent components using props?

Yes, data can be passed from a child component to a parent component using props. Props are a way for a parent component to pass data to a child component.

For example, if a parent component has a state called count and wants to pass the count to a child component, it could define the count as a prop and then pass the prop to the child component like so:

//Parent Component:

render() {
  const { count } = this.state;

  return (
    <ChildComponent count={count} />
  );
}

//Child Component:

render() {
  const { count } = this.props;

  return (
    <div>{count}</div>
  );
}

How can you pass data from children to parents?

  • Data can be passed from a child component to a parent component using a callback function. A callback function is a function that is passed as an argument to another function.

  • In order for a parent component to receive data from a child component, the parent component must define a callback function as a prop and then pass the callback function to the child component. The child component can then call the callback function and pass it data.

  • For example, if a parent component wants to receive data from a child component, it could define a callback function and then pass the callback function to the child component like so:

//Parent Component:

handleData = (data) => {
  // Do something with the data
}; 

render() {
  return (
    <ChildComponent onData={this.handleData} />
  );
}


// Child Component:

handleClick = () => {
  const data = { message: 'Hello World!' };

  this.props.onData(data);
};

render() {
  return (
    <button onClick={this.handleClick}>Send Data</button>
  );
}