What is state and props in React? [In Depth Explained]

In Reactjs we develop different types of the component to develop complex UI. To create data-flow between different component React uses state and porps. Because of state and props it is able to render a component with dynamic data.

Props

Props stand for properties. It is an object which looks like HTML attributes and also works similarly to the HTML attribute. Props are immutable i.e. we cant not change the value of props. Props are used for sending the data from one component to another component. They are treated as pure JavaScript function whose parameter value cannot be changed

Let’s have a quick look at how props work:

import React from 'react';
import './state_prop.css';


class Demo extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
        <div className="App">
            <img src = {this.props.img_url}/>
            <p className="text-primary"> {this.props.time} </p>
        </div>
        );
    }
    
}

export default Demo;

The above code is simple. We have a class Demo that renders the value of props passed to it which is nothing but an image file and the current time. Now let’s look at our index.js file where we have initialized our props value.


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Demo from './state_prop';
import * as serviceWorker from './serviceWorker';

var date = new Date()
var t = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()

ReactDOM.render(<Demo 
    img_url = {require('./img1.jpg')}
    time = { t }
        />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

As you can see we have passed to props img_url and time.As we have discussed earlier props are immutable so if you try to change the value of the props it will give you an error.

If you have done everything right the output component will somewhat look like this:

State

State are used to store the data of that component. They are used to update components whenever some event occurs for example clicking button, pressing some key etc. Whenever some event occur the component will re-render itself. State are mutable i.e. we can change the value of state by using setState() function. Whenever a class inherits the class React. Component it’s constructor will automatically assign attribute state to the class with initial value is set to null.

Let’s see how the state works with an example. We will try to modify our last component but here instead of displaying time once we will use state to update the clock on every second.

import React from 'react';
import './state_prop.css';


class Demo extends React.Component {
    constructor(props) {
        super(props);
        this.state = { time: null};
    }
    componentDidMount()
    {
        setInterval( () => {
            var date = new Date();
            this.setState( {
                time : date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
            })
        },1000)

    }

    render() {
        return (
        <div className="App">
            <img src = {this.props.img_url}/>
            <p className="text-primary"> {this.state.time} </p>
        </div>
        );
    }
    
}

export default Demo;

As you can see the initial value of the state is null. We have used here setInterval() function to trigger the event in every second. As soon as the event is triggered it changes the value of the state by using setState() function and the component re-renders itself.

Try this, if everything went fine you will see component updating its value every second.

Sharing is caring!

Leave a Comment

Your email address will not be published. Required fields are marked *

shares
Scroll to Top