Getting Started with React - Lesson #13

Using React's useState() for Component Data

Building applications and websites consists of showing information to our users. We'll usually grab information from a database or API and then displaying it to our users.

With our modern applications, we also expect these applications to react to our interactions like clicks and typing into forms. We expect modern applications to (ahem) react quickly. For instance, if we have a search box, users expect to see new search results whenever they type into the box.

React gives us the tools to quickly update our UI so that users get the most current information.

Let's talk about how React helps to update the UI thanks to React State.

React State is React's ability to watch certain variables and update the UI if that variable changes. If we store a string called message in React State, whenever that message changes, React will update the UI.

Whenever React sees a change in state, it will re-render the component.

Let's add the message variable. In order to add a variable to React State, we need to use a tool React provides us called useState().

jsx
function App() {
    // add a message variable to state
  // set the message to "hey there"
    const [message, setMessage] = useState('hey there');

    // our template where we display the message
    return <div>{message}</div>;
}

This syntax may seem foreign if you aren't familiar with destructuring. This is the syntax to destructure an array. The useState() function returns an array with two parts:

  1. The variable
  2. A function to update that variable

We can display the message with JSX: {message}

Whenever we use the setMessage() function, React will automatically update the UI and re-render its template.

In order to use that function, we need to create a button with an event listener. We'll do it quickly here, but we will talk more about event handlers in the next lessons.

jsx
function App() {
    // add a message variable to state
  // we will set the starting value
    const [message, setMessage] = useState('hey there');

    // our template where we display the message
    return (
        <div>
            <p>{message}</p>
    
            <button onClick={() => setMessage('my new message')}>
                Update Message
            </button>
        </div>
    );
}

We have now created a button that will update the message on a click. Since we are using setMessage('my new message'), React will re-render the template with the new data.

You may be wondering why we can't just add a variable to a React component and update that. React tries to be as efficient as possible. It does this by only watching the certain values we tell it to. We tell React which variables to keep an eye out for with useState.

If we tried to store information in a variable and update it, React would not update our UI. This example would not work.

jsx
// 🚫 this wont work since were not using useState

function App() {
    let message = 'hey there everyone';

    // function to update the message wont re-render our component
    function updateMessage() {
        message = 'my new message';
    }

    // our template where we display the message
    return (
        <div>
            <p>{message}</p>
    
            <button onClick={updateMessage}>
                Update Message
            </button>
        </div>
    );
}

This will work though:

jsx
// ✅ this will work since we use useState()

function App() {

    // add a message variable to state
    const [message, setMessage] = useState('hey there');

    // this will re-render our component and update the ui
    function updateMessage() {
        setMessage('my new message');
    }

    // our template where we display the message
    return (
        <div>
            <p>{message}</p>
    
            <button onClick={updateMessage}>
                Update Message
            </button>
        </div>
    );
}

The reason we need React State is that React needs to know when to update our UI.

By default, useState will instantiate the variable as undefined. If we wanted to provide some information to the variable, we would pass it as a parameter to useState.

jsx
const [message, setMessage] = useState('I am a default message');

We can store all sorts of types in state. We have shown a string, but we can also do numbers, booleans, arrays, and objects.

jsx
// number
const [age, setAge] = useState(32);

// boolean
const [isActive, setIsActive] = useState(false);

// array
const [people, setPeople] = useState(['chris', 'kap']);

// object
const [pokemon, setPokemon] = useState({ name: 'pikachu' });

We'll talk about using more types in the following lessons.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.