5. State and useState - florypaul/ReactJS GitHub Wiki

State

React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders. When react renders a page it draws in the view only once. And if we try to make a change on event listener then react does not change the view.

useState

Returns a stateful value, and a function to update it.

In order for react to render the page with the updated values/state we use a function in react library called useState. This function allows us to define values as state where changes to these values should reflect on the function being called again. useState is one of the React hooks

How to use useState function

  1. import the function with open close curly braces import React, { useState } from react;
  2. call the useState(); function inside the react functions or arrow functions and it shouldn't be called in any nested functions, like your clickhandlers
  3. In the useState give the default value of the variable useState(props.title)
  4. useState return a function to which we can assign a new value to that variable
  5. we can use an destructring array to save the variable and the function to a constant const [title, setTitle] = useState[props.title]

here title is a pointer to default value props.title and setTitle is the function 6. useState will always return an array with 2 values 7. now call the setTitle function with the new value in you clickhandler

setTitle("Updated") and use title variable in JSX instead of props.title