Data Engineer Masters Program (10 Blogs) Become a Certified Professional

ReactJS State Guide: Exploring SetState, Props, and State

Published on Oct 14,2024 25 Views

Sunita Mallick
Experienced tech content writer passionate about creating clear and helpful content for... Experienced tech content writer passionate about creating clear and helpful content for learners. In my free time, I love exploring the latest technology.

ReactJS is the JavaScript library to develop UI components. It is used by many companies like Netflix, Airbnb, The New York Times, etc. A focal aspect that has contributed to the popularity of MySQL is its capability of delivering results in the shortest time possible. React applications are generally faster than those developed from older frameworks, such as Angular.

In this blog, we will look at one of the main constituents of building dynamic webapps in ReactJS, that is “state.”. At the end of this post, you will be able to explain how state operates, the use of the setState() function, and state versus props.

What Is ‘State’ in ReactJS?

State is a native object in ReactJS that stores data or information about the component. This data can be changeable, which implies that its value can change as days, weeks, or months progress. In case the status changes, then React will repaint the component in order to give the new information. 

Let’s consider state as the’storages’ of one of the components—it contains information that can be modified by the actions performed by a user or by other events taking place within the application.

For instance, in the case of Java, where it can be used to create graphical user interfaces, a click of the button may transform the component’s state. When this happens, React updates the output of the component to match the new state.

Here’s a simple example of how state works in a React component:

class Greetings extends React.Component {
  state = {
    name: "World",
  };

  updateName = () => {
    this.setState({ name: "React Learner" });
  };

  render() {
    return (
      <div>
        <h1>Hello, {this.state.name}!</h1>
        <button onClick={this.updateName}>Change Name</button>
      </div>
    );
  }
}

In this example, the component’s state starts with the value “World”. When the button is clicked, it changes the state to “React Learner”, and React automatically re-renders the component to reflect the new value.

If you want to dive deeper into React, consider taking a comprehensive React Js Training to enhance your knowledge.

The setState() Method

State in React can be updated using the setState() method. This method is vital because it tells React to update the component and re-render the view with the new state.

Let’s look at an example:

class Bike extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      make: "Yamaha",
      model: "R15",
      color: "blue",
    };
  }

  changeBikeColor = () => {
    this.setState({ color: "black" });
  };

  render() {
    return (
      <div>
        <h2>My {this.state.make}</h2>
        <p>
          It is a {this.state.color} {this.state.model}.
        </p>
        <button onClick={this.changeBikeColor}>Change Color</button>
      </div>
    );
  }
}

 

In this case, setState() is used to change the color of the bike from ‘blue’ to ‘black.’ Every time there is change in the state, React will re-render this component to reflect the color change.

Key Points about setState():

  • Updates the state: The method that is involved with updating the state object is known as setState().
  • Re-renders the component: Whenever setState() is called, React knows that the state has been updated and needs to re-render the component.
  • Shallow merge: The setState() method simply copies the new state to the previous state, skipping any array or object properties if they have the same reference. This means only those parts of the state that have been changed are updated.

State vs. Props

Understanding the difference between state and props is crucial for working with React components. Both are used to manage data within a component, but they serve different purposes.

FeatureStateProps
Use CaseState is used to manage dynamic data.Props are used to pass data to child components.
MutabilityState can change over time.Props are immutable (cannot be changed).
ComponentState is only used in class components.Props can be used in both functional and class components.
UpdateUpdated using event handlers or setState.Set by the parent component and cannot be changed by the child component.

Let’s say we have two components: a parent component and a child component. The parent component passes props to the child, but only the child component manages its own state.

class Parent extends React.Component {
  render() {
    return <Child name="React Learner" />;
  }
}

class Child extends React.Component {
  state = {
    age: 25,
  };

  increaseAge = () => {
    this.setState({ age: this.state.age + 1 });
  };

  render() {
    return (
      <div>
        <h1>{this.props.name}</h1>
        <p>Age: {this.state.age}</p>
        <button onClick={this.increaseAge}>Increase Age</button>
      </div>
    );
  }
}

 

In this example, the parent component passes the name prop to the child component. However, the child component manages its own state (the age), which can change when the button is clicked.

Key Differences:

The state in react is for smaller pieces of data that can change within a component, for example, a counter or input from the user.

It is with the help of Props that one component can pass data to another component. They are generally set by the parent component and may not be modified by the child component.

Conclusion

The state in react is one of the core components of ReactJS, which helps the components handle dynamic data. Therefore, the method known as setState() guarantees that if the state has to be changed in any given component, it should be rendered again to display new data. It is important to define the difference between the state and props if one is to deal with the flow of data in the React applications.

Mastering these concepts puts you in a good starting point for providing better and more effective user interfaces that are interactive. If you want to delve further into the topic, you can engage more through this ReactJS training.

FAQs

What is state in ReactJS?
State is an object that holds data within a component. It controls how the component renders and behaves.

How does setState() work in React?
setState() updates the component’s state and triggers a re-render to display the new data.

Can I change props in React?
No, props are immutable and cannot be changed by the component receiving them.

What is the main difference between state and props?
State changes within the component, while props are passed from the parent and cannot be modified by the child.

5. Is setState() asynchronous?
Yes, setState() is asynchronous, meaning updates are batched for performance reasons.

 

Upcoming Batches For Data Engineer Masters Program
Course NameDateDetails
Data Engineer Masters Program

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

ReactJS State Guide: Exploring SetState, Props, and State

edureka.co