React State Explained Simply

Explaining state is a very difficult concept simply because it is so broad. It is sometimes best to explain complicated things by explaining what they are NOT:

State Is NOT:

  • Menu Items
  • Footers
  • Company Logo
  • Contact Page

These items are not state because they don’t change from page to page and are static.

State IS:

  • Data from a database
  • API response displayed in a list
  • Most blog content
  • Messages in a chat

These are all examples of state because they are being obtained from a database, change from page to page, and can also change while you are even on the page.

In react, state is sometimes described as a snapshot of data on a web page and changes during a re-render.

Why Setting State Triggers Renders

“Rendering” means that react is calling your component and this is pretty much a “picture”.

A snapshot or picture is static and does not change. Web apps change in the modern era changes very frequently.

By triggering a render each time state changes, this is ensuring we can have interactive web pages.

Unlike photos, the return UI is interactive and includes logic like event handlers

When react re renders a component:

  1. React calls your function again.
  2. 2. You function returns a new JSX snapshot you’ve returned.

In this example, you might expect that clicking the “ADD” button would increment the counter 2X:

export default function Counter() {
  const [number, setNumber] = useState(0);

  return (
    <>
      <h1>{number}</h1>
      <button onClick={() => {
        setNumber(number + 1);
        setNumber(number + 1);
      }}>+3</button>
    </>
  )
}

But notice that it only increments once! This is because setting state only changes it for the next render!

During the first render, number was 0. When onClick causes the component to re-render, the value of number is still 0 event after the setNumber(number + 1) was called.

Leave a Reply

Your email address will not be published. Required fields are marked *