React State

React components use and render two different kinds of data: props and state. Props is data that is passed into a component from its parent. It is very unusual for the value of a prop to change once it's passed into a component. State is data that is specific to the component that created it. This data is expected to change usually as the result of a user event.

One way to think of the difference is:

  • Props is data passed into a component from its parent and should not be changed.
  • State is data created within a React component and can be changed within a component using the useState hook

In the example below, state is being used to track and display the number of times a button has been clicked.

import React, { useState } from 'react'
function Counter () {
const [count, setCount] = useState(0)
const handleClick = () => {
setCount(count + 1)
}
return (
<div>
<h1>State FTW!</h1>
<p>Current count is: {count}</p>
<button onClick={handleClick}>Increase</button>
</div>
)
}
export default Counter

There are a number of things to notice about the sample above.

  • When we call the useState hook, we pass it the starting value for our state. In this case we wish our count to start at 0.

  • The component creates an identifier (count) to hold the value of our state and a function to update the state (setCount).

  • In the handleClick function, setCount is passed the next value we wish the state to update to.

  • When setCount is used to update the state value, it triggers a render. This is how React knows to render the component again and update the DOM.

For more information about how to use state, see the Using the State hook section in the React Hooks documentation.