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.