State: A Components Memory

Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” should put a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.

Difference between constant variables and state in component

First, take an example of a constant variable usage in a component

funcion CountBTN() {
		const count = 0;
		
		function handler() {
				count = count + 1;
		}
		
		return (
				<button onClick={handler}>{count}</button>
		);
}

When you click on that button, the counter does not update. The handler is updating the local variable, but two things prevent that change from being visible.

  1. Local variables don’t persist between renders. When React renders this component a second time, it renders it from scratch—it doesn’t consider any changes to the local variables.
  2. Changes to local variables won’t trigger renders. React doesn’t realize it needs to render the component again with the new data.

To update a component with new data, two things need to happen:

  1. Retain the data between renders.
  2. Trigger React to render the component with new data (re-rendering).

The useState Hook provides those two things:

  1. state variable to retain the data between renders.
  2. state setter function to update the variable and trigger React to render the component again.

Now with the state, clicking the count button, it will increase.

funcion CountBTN() {
		const [count, setCount] = useState();
		
		function handler() {
				setCount(count => count + 1);
		}
		
		return (
				<button onClick={handler}>{count}</button>
		);
}

How it works

Every time your component renders, useState gives you an array containing two values: