States and props in ReactJS

·

4 min read

What is State?

The state is an initial value set for a component, which is used for interactivity.

In Class Components Using constructor, the state of a component is created and initialized using this.state as follows:

constructor() {
     super();
     this.state = { counter: 1 };
}

In the above code, the state 'counter' is set to 1 and 'counter' would be accessed as this.state.counter.

As the user-defined component extends React.Component, it becomes a child component of it. Hence, whenever a child component has a constructor, it has to call the parent class's constructor using the super() method. And super() method should be the first statement within a constructor.

How to Handle Async State updates in React:

1) In Class Components: If you want update the state and want to do operation on that updated State

  • Either Use a Callback function in setState() method, that call back fn will be executed after the state update.
  • Pass the new updated state value upfrontly in the upcoming operation

2) In functional components:

Since Fnal Components works on the Closures so they only get updated state value the next render cycle .

So to get latest updated state value we can use below things :


Props

When data is passed from parent component to child component, it becomes property of child component.

1) In Class Components :

  • In order to access props within the constructor, we need to pass props as an argument to both the constructor() and super() .

2) In functional Components :

  • Define the props in child component and access them either by destructing or by props.name.

Using props to send data back to parent component from child component :

  • we can also pass data from the child to the parent component. If the child component wants to send data to the parent component, it can send it by invoking a function that is passed as props from the parent component.
  • STEPS -> i) Pass a handler function (Define in Parent comp) a Prop to child component .
                 ii) Call that handler function from child component.  
    

consider Parent component below :

import React from 'react';
import Child from './Child';
class App extends React.Component {
        constructor() {
          super()
          this.state = {
            name: 'Annnii'
          }
        }
        update = (value) => {
         let newValue = value;
         this.setState({name:newValue})
        }
        render() {
          return ( <React.Fragment>
            <h1>{this.state.name}</h1><br/><br/>
            <Child nameValue={this.state.name} update={this.update}/>
          </React.Fragment>)
        }
      }
export default App;

The Parent component contains the state 'name', which gets updated in the child component as shown below::

import React from 'react';
class Child extends React.Component {
    constructor() {
        super()
        this.state = {
            nameValue:null
        }
    }
    handleChange = () => {
        let newValue = 'June'
        this.setState({nameValue: newValue})
        this.props.update(newValue)
    }
    render() {
        return(<React.Fragment>
            <button onClick={this.handleChange}>Change</button>
        </React.Fragment>)
    }
}
export default Child;
  • In the child component on clicking of the change button, the value of the state 'nameValue' changes to 'June' and the same value is sent to the parent component by calling the update() method from Child component as this.props.update(newValue).

  • The update() method is a prop passed to the Child Component.

  • The Parent component gets the updated value from the child and updates its state.


Component types

  1. Functional Component:

    • Created as a simple JavaScript function
    • It just returns the valid JSX
  2. Class Component:

    • Created as a class component
    • It encapsulates interaction logic as well as renders data

Accessing the child nodes :

  • To access these child nodes of a component, React uses this.props.children.
  • React.Children provide utilities to deal with this.props.children.
  • React.Children.map can be used to iterate this.props.children as follows:
    React.Children.map (this.props.children, function fn (arg) { })

Function fn() will be invoked on every immediate child contained within children. If children is null or undefined, fn() returns null or undefined.


  • Default Props

i) Validating props using PropTypes

ii) Using different validators