Open In App

Lifting State up in ReactJS

Prerequisite: ReactJs, State, Props

Lifting up the State: As we know, every component in React has its own state. Because of this sometimes data can be redundant and inconsistent. So, by Lifting up the state we make the state of the parent component as a single source of truth and pass the data of the parent in its children.



Time to use Lift up the State: If the data in “parent and children components” or in “cousin components” is Not in Sync.

Example 1: If we have 2 components in our App. A -> B where, A is parent of B. keeping the same data in both Component A and B might cause inconsistency of data. 



Example 2: If we have 3 components in our App.

        A
       / \
      B   C

Where A is the parent of B and C. In this case, If there is some Data only in component B but, component C also wants that data. We know Component C cannot access the data because a component can talk only to its parent or child (Not cousins).

Problem: Let’s Implement this with a simple but general example. We are considering the second example.

Complete File Structure:

Approach: To solve this, we will Lift the state of component B and component C to component A. Make A.js as our Main Parent by changing the path of App in the index.js file

Before:

import App from './App';

After:

import App from './A';

Filename- A.js:




import React,{ Component }  from 'react';
import B from './B'
import C from './C'
   
class A extends Component {
  
  constructor(props) {
    super(props);
    this.handleTextChange = this.handleTextChange.bind(this);
    this.state = {text: ''};
  }
  
  handleTextChange(newText) {
    this.setState({text: newText});
  }
   
  render() {
    return (
        <React.Fragment>
          <B text={this.state.text} 
             handleTextChange={this.handleTextChange}/>
          <C text={this.state.text} />
        </React.Fragment>
    );
  }
}
  
export default A;

Filename- B.js:




import React,{ Component } from 'react';
  
class B extends Component {
  
constructor(props) {
    super(props);
    this.handleTextChange = this.handleTextChange.bind(this);
}
  
handleTextChange(e){
    this.props.handleTextChange(e.target.value);
}
  
render() {
    return (
        <input value={this.props.text} 
               onChange={this.handleTextChange} />
    );
}
}
      
export default B;

Filename- C.js:




import React,{ Component } from 'react';
  
class C extends Component {
  
render() {
    return (
        <h3>Output: {this.props.text}</h3>
    );
}
}
      
export default C;

Output: Now, component C can Access text in component B through component A.


Article Tags :