How to manage state within a React component

0 votes
With the hep of code can you tell me How to manage state within a React component?
6 days ago in Node-js by Nidhi
• 13,180 points
40 views

1 answer to this question.

0 votes

In React, state is managed differently in functional components and class-based components. Here's a precise explanation for both:

1. Managing State in Functional Components

Use the useState hook to manage state.

import React, { useState } from 'react';

function MyComponent() {

  // Declare state variable and setter function

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

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </div>

  );

}

export default MyComponent;


2. Managing State in Class-Based Components

Use the this.state object and this.setState method.


import React from 'react';

class MyComponent extends React.Component {

  // Initialize state in the constructor

  constructor(props) {

    super(props);

    this.state = {

      count: 0,

    };

  }

  // Method to update state

  increment = () => {

    this.setState({ count: this.state.count + 1 });

  };

  render() {

    return (

      <div>

        <p>Count: {this.state.count}</p>

        <button onClick={this.increment}>Increment</button>

      </div>

    );

  }

}

export default MyComponent;

answered 6 days ago by anonymous

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to manage side effects in a React application?

Side effects like data fetching, subscriptions, or ...READ MORE

answered Mar 18 in Node-js by Anvi
54 views
0 votes
1 answer

How to implement component lifecycle methods in a Class Component?

To implement component lifecycle methods in a ...READ MORE

answered 6 days ago in Node-js by anonymous
45 views
0 votes
1 answer

How to handle React events like button clicks?

To handle React events like button clicks, ...READ MORE

answered 6 days ago in Node-js by anonymous
40 views
0 votes
1 answer

How to create and manage forms in React?

You need to handle user input, manage ...READ MORE

answered 6 days ago in Node-js by anonymous
38 views
0 votes
1 answer

How to apply inline styling to a React component?

You apply inline styling in React using ...READ MORE

answered 6 days ago in Node-js by anonymous
43 views
0 votes
1 answer

How to manage component state in a Music Shop Application?

You can manage component state in a ...READ MORE

answered 6 days ago in Node-js by anonymous
44 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP