What is a component state?
A component state allows us to manage some data related to that component. When ever the state of a component changes, the component is automatically re-rendered by react.
A state is a special property provided by react and it is only available to components that are created by extending React.Component class and not to the components created by defining a function(Remember the two methods of creating components)
We should use the state with care(not over use it) since manipulating the state causes the DOM to be rendered again which makes the application unpredictable and hard to manage.
Example,

import React, {Component} from 'react';

class Website extends Component {
    state: {
      website: 'codippa.com',
      technology: 'react'
    }
    // define render method
    render(){
        return(
            // component elements
            <div>
                <h1>{this.state.website}</h1>
                <p>Learning {this.state.technology}</p>
            </div>   
        );
    }
}
export default Website;

In the above component, there is a state property  which is a plain javascript object having two properties. These properties can be accessed inside the JSX code using this since the state is a class level property. Note that state is a special property and its name is significant. Though the above example accesses the state object but the actual use of this property is to incorporate events in react components which is explained next.

Events
An event is an action performed by user on a page such as a click, a text typed, right click etc. Handling events is the most vital part of an application. Handling event means performing some action when the event occurs.

Following  are the steps required to handling events in react.
1. Create a function which will contain the event handling logic.
2. Associate this function with the event type and bind it with the element which should be event enabled.

Also, following points should be remembered while writing event handling logic.
1. Event handler functions in react should be named in camel case. Example, getInput, checkName etc.
2. When binding this function to the event, it should not be written as a string as we do in normal javascript.
Example, onClick = {getInput}. Note there are no quotes around the function name.
3. Parenthesis should not be present after function name when associating it with the event. If parenthesis are added, then the function will be called on page load itself.
4. Function name should be enclosed between { and } as shown in the above example.
Event Handling Example
Suppose in  the above code example, we add a button. When this button will be clicked, the value of technology field will change to python and the message will change to Learning python. Following the above steps, below changes need to be done.
1. Add a function handleClick which will change the value of techonology  key in state object.
2. Associate this function with click event of button using onClick attribute.

import React, {Component} from 'react';

class Website extends Component {
    state: {
      website: 'codippa.com',
      technology: 'react'
    }

    // click event handler function
    handleClick = ()=> {
        this.setState({technology: 'python'});
    }

    // define render method
    render(){
        return(
            // component elements
            <div>
                <h1>{this.state.website}</h1>
                <p>Learning {this.state.technology}</p>
                <button onClick = {this.handleClick}>Change</button>
            </div>   
        );
    }
}
export default Website;

There are no quotes and parenthesis around function name when it is associated with the onClick attribute of button and it is enclosed between { and }.
Notice that we are changing the value of state property using setState method. This method takes an object which contains only the values which we want to change. This way react will only update parts of DOM which are modified and not the whole DOM.
You might be thinking that why didn’t we update the value of technology directly in the state object without using setState method like this: this.state.technology = 'react';
The answer is because you should not modify state object directly. It should be modified only using setState method. If the state object is modified directly, then react will not detect the changes and it will not update the DOM and thus, you will not see the desired changes. Further, when state object is modified directly, you will see a warning on the browser console

Do not mutate state directly. Use setState() react/no-direct-mutation-state

setState can also accept an arrow function which should return an object containing the state values to be updated. Advantage of using an arrow function in setState is that you can gain access to the previous or existing state values because this arrow function can receive an argument which is populated with the existing state object. Example,

this.setState((prev) => {
   console.log(prev.technology); // prints react
   return {technology: 'python'} // update state
 }
);

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.