What is the difference between State and props in React Js ?

devquora
devquora

Posted On: May 29, 2024

 

Props are shorthand for properties.they are very similar to an argument is passed to a pure javascript function. Props of the component are passed from parent component which invokes component. During a component’s life cycle props should not change consider them as immutable.In React all props can be accessible with this.props.

import React from 'react';
class Welcome extends React.Component {
  render() {
    return <h1>Hello {this.props.name}</h1>;
  }
}
const element = ;

State are used to create dynamic and interactive components in React.State is heart of react component that makes it alive and determines how a component renders & behaves.

// simple state example 
import React from 'react';
class Button extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
  }

  updateCount() {
    this.setState((prevState, props) => {
      return { count: prevState.count + 1 }
    });
  }

  render() {
    return (<button
              onClick={() => this.updateCount()}
            >
              Clicked {this.state.count} times
            </button>);
  }
}

export default Button;

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    React Js Interview Questions

    What is ReactJS ?

    ReactJS, created by Facebook, is a JavaScript library for crafting dynamic, stateful, and reusable user interface components. It's renowned for simplifying the presentation layer of web and mobile app..

    React Js Interview Questions

    List some advantages of ReactJS ?

    React.js offers efficiency with its virtual DOM, simplifies JavaScript with JSX, provides developer tools, enhances SEO, and facilitates UI test cases effortlessly...

    React Js Interview Questions

    What are Components in ReactJS ?

    React components divide UI into reusable pieces, akin to JavaScript functions. They accept props and return elements for screen rendering. Below is an ES6 class-based component showcasing a welcome me..