0% found this document useful (0 votes)
9 views

React State

Uploaded by

Ashish Panda
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

React State

Uploaded by

Ashish Panda
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

State

------
Purpose of State: The state in React is a built-in object used to hold data or
information about a component. A component's state can change over time, and when
it does, the component re-renders to reflect those changes.

Dynamic Nature of State: The state can change in response to user actions, system-
generated events, or other factors. Changes in state drive the behavior of the
component and influence how it renders.

Characteristics of State: The state is an object that contains information that may
vary over the lifespan of the component.
It is private to the component, meaning that the component itself has control over
its state.
Unlike props, which are read-only and passed to a component, the state is
controlled solely by the component that owns it.

State in Class Components: State is typically used in class components, where you
can initialize it in the constructor. Class components have a built-in state object
that allows them to manage and update their internal state.

Updating State: You can update the state using the setState() method provided by
React.
The setState() method enqueues a request to update the state, and React will later
re-render the component with the updated state.

Multiple Properties in State: The state object can contain multiple properties,
each representing a piece of information that the component needs to keep track of.

Comparison with Props: State is similar to props in that both are used to manage
data in a component.
However, unlike props, which are passed to a component and are read-only, the state
is controlled internally by the component that owns it.

Creating the state Object


--------------------------
There are two way to initialize state in React Component: -
1.Directly inside class (Without Constructor)
2.Inside the constructor (With Constructor)

1. Directly Inside Class (Without Constructor):


-----------------------------------------------
In modern React (with versions that support class properties or using functional
components with hooks), you can initialize state directly outside the constructor
using class properties.

This approach eliminates the need for a constructor and is a concise way to define
the initial state.

Here's an example:

import React, { Component } from 'react';


class MyComponent extends Component {
state = {
// state properties go here
property1: 'value1',
property2: 'value2',
};
// ... rest of the component
}

2. Inside the Constructor (With Constructor):


---------------------------------------------
In earlier versions of React or when working with class components, you can use the
constructor to initialize the state.

Here's an example:

import React, { Component } from 'react';


class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
// state properties go here
property1: 'value1',
property2: 'value2',
};
}
// ... rest of the component
}

Note: Inside the constructor, you call super(props) to ensure that the base class
(Component) constructor is called.

Using the state Object


-----------------------
Refer to the state object anywhere in the component by using the
"this.state.propertyname" syntax.

Changing the State Object:


--------------------------

To modify or update the values in the state object, you use the this.setState()
method. Directly modifying the state using this.state is not recommended because it
may not trigger the necessary updates and re-renders.

The setState() Method: The setState() method is a built-in method provided by React
to update the state of a component. When you call this.setState(), React enqueues
the updates made to the component state. It doesn't immediately apply the changes
but schedules them for an asynchronous update.

Updating State in Response to Events: State changes often occur in response to


events, such as user interactions, server responses, or changes in props. Event
handlers, like those for button clicks or form submissions, can invoke
this.setState() to update the state based on user actions.

Re-rendering and render() Method: When you use this.setState(), React re-renders
the component and its children with the updated state. The render() method is
called again, generating the updated output based on the new state values.

Ensuring Component Awareness: It's crucial to always use the this.setState() method
rather than directly modifying the state object. This ensures that React is aware
of the state changes and can manage the component's lifecycle and updates
appropriately.

Dynamic UI Changes: As the state changes, the component re-renders, leading to


dynamic updates in the UI. This is a fundamental aspect of React's declarative
nature, where you describe how the UI should look based on the current state.
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
// Initialize state with a count property
this.state = {
count: 0,
};
// Binding the custom method to the class instance (for the older
syntax)
// this.handleIncrement = this.handleIncrement.bind(this);
}

// Custom method to handle incrementing the count


handleIncrement = () => {
// Use setState to update the count in a safe and asynchronous
manner
this.setState({
count: this.state.count + 1,
});
};

render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}

export default Counter;

Example: 2
-----------

import React, { Component } from 'react';

class Counter extends Component {


constructor(props) {
super(props);

// Initialize state with a count property


this.state = {
count: 0,
};
}

// Custom method to handle incrementing the count


handleIncrement = () => {
// Use setState with a function to update the count based on the previous state
this.setState((prevState) => {
return {
count: prevState.count + 1,
};
});
};
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default Counter;

Note: Using a function with "setState" is a recommended practice when the new state
depends on the current state, as it helps avoid potential race conditions and
ensures the correct sequence of state transitions.

Race Condition
---------------
A race condition in React occurs when there are multiple asynchronous operations
that compete to update the same piece of state or data, and the outcome becomes
unpredictable because of the timing of these operations.

For Ex:

import { Component } from "react";


export default class App extends Component {
constructor() {
super();
this.state = {
counter: 1
}
}
changeDate = () => {
// Issue: setState is asynchronous/
// This may not work as expected
this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });
}
render() {
return (
<>
<p>Counter : {this.state.counter}</p>
<button type="button" onClick={this.changeDate} >Update</button>
</>
)
}
}
In the changeDate method, calling setState multiple times like this may not result
in the expected behavior because setState is asynchronous. The state updates might
be batched, and the state might not be updated immediately.

To ensure that the state updates are based on the current state, you should use the
functional form of setState:
changeDate = () => {
// Use the functional form to ensure correct state updates
this.setState((state) => ({ counter: state.counter + 1 }));
this.setState((state) => ({ counter: state.counter + 1 }));
this.setState((state) => ({ counter: state.counter + 1 }));
this.setState((state) => ({ counter: state.counter + 1 }));
this.setState((state) => ({ counter: state.counter + 1 }));
}

This way, each call to setState takes the current state into account, preventing
unexpected behavior due to the asynchronous nature of state updates.

setState() accepts a callback


------------------------------

The setState function in React can take a callback as its second argument. This
callback is invoked after the state has been updated and the component has been re-
rendered. The callback receives the updated state as an argument.

import { Component } from 'react';


class ExampleComponent extends Component {
constructor() {
super();
this.state = {
counter: 0,
};
}

incrementCounter = () => {
// Using the callback function with setState
this.setState(
(prevState) => ({
counter: prevState.counter + 1,
}),() => {
// Callback function is invoked after the state is updated and the
component is re-rendered
console.log('Updated state:', this.state.counter);
}
);
};
render() {
return (
<div>
<p>Counter: {this.state.counter}</p>
<button onClick={this.incrementCounter}>Increment</button>
</div>
);
}
}

export default ExampleComponent;

Reconciliation proces
---------------------
The reconciliation process is a crucial aspect of React's virtual DOM and its
ability to efficiently update the actual DOM. Here's a more detailed explanation of
the reconciliation process:

State Change Trigger: The reconciliation process begins when there is a change in
the component's state. This change can be initiated by calling the setState()
method.
Creation of New Virtual DOM Tree: React creates a new virtual DOM tree that
represents the updated state and the corresponding UI elements. This new tree is a
lightweight, in-memory representation of the component's structure.

Differential Algorithm: React utilizes a differential algorithm during the


reconciliation process. It compares the new virtual DOM tree with the previous one
to identify the differences or changes in the component's state.

Efficient DOM Updates: Instead of directly manipulating the actual DOM for every
change, React calculates the minimal set of changes needed to update the UI. This
is one of the key reasons React is considered fast and efficient.

Reconciliation Strategy: React employs a strategy known as "reconciliation" to


determine the most efficient way to update the DOM. It aims to minimize the number
of manipulations performed on the actual DOM, only updating the parts that have
changed.

Component Rendering: Based on the identified differences, React decides how to


update the component's UI. It might involve adding, updating, or removing DOM
elements. React ensures that the resulting DOM structure accurately reflects the
current state of the component.

Batching Updates: React may batch multiple updates together for improved
performance. Instead of updating the DOM after each individual state change, React
can group several changes and apply them in a single batch, reducing the overall
number of DOM manipulations.

Rendering to the Actual DOM: Once the changes are determined, React updates the
actual DOM with the calculated minimal set of changes. This process is much more
efficient than directly manipulating the DOM for every state change.
By employing this reconciliation process and the virtual DOM, React optimizes the
rendering and updating of components, resulting in a more responsive and performant
user interface.

You might also like