Updating the State of functional Components

To update the state of a Functional Component we will be using the useState Hook. Functional component can not access the states directly. Hooks in functional components help to access and modify the state of the component.

Syntax:

const [state, setState] = useState({text:'Default value of the text state'});

  • Pass the ‘text’ state to the JSX element using ‘{state.text}’ method.
  • Update the state on a specific event like button click using the ‘setState’ method. The syntax is given below :
setState({text:'Updated Content'})

Example: This example use React JS hooks to access and update the state of component in the funcional component.

Javascript




// App.js file
 
import React, { useState } from "react";
 
function App() {
    const [state, setState] = useState({
        text: 'Welcome to w3wiki'
    });
    return (
        <div>
            <h1>{state.text}</h1>
            <button onClick={() => setState({
                text: 'Subscription successful'
            })}>
                Go Premium
            </button>
        </div>
    );
};
 
export default App;


Step to run the application: Open the terminal and type the following command. 

npm start

Output: This output will be visible on the http://localhost/3000 on the browser window.



How to update the State of a component in ReactJS ?

To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content.

Similar Reads

Prerequisites:

NPM & Node.js React JS React State React JS Class Components React JS Functional Components...

Approach:

The State is an instance of a React Component that can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. The state of a component can be updated during its lifetime....

Steps to Create React Application:

Step 1: Create a React application using the following command:...

Approach 1: Updating the State of Class-Based Components

To update the state of a class based component we will be using the given setState method. Class based component can directly access the states using this keyword....

Approach 2: Updating the State of functional Components

...

Contact Us