DEV Community

grant-ours
grant-ours

Posted on

useState Hook

React Hooks useState

What Are Hooks?

Hooks are new! It was a feature introduced in React 16.8. It allows you to use state and other React features without writing a class. Hooks are functions which "hook into" React features. It does not work inside classes.

When Should I useState vs Props?

Choosing whether to use state vs props comes down to "who owns this data?". If data is managed by one component, but another component needs access to that data, you'd pass the data from the one component to the other component via props.

If a component manages the data itself, it should use state to manage it.

Example

I'm going to show how to use state in a simple cookie clicker app.

Declaring State

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "cookies"
  const [cookies, setCookies] = useState(0);
Enter fullscreen mode Exit fullscreen mode

What Does Declaring State Do?

It declares a “state variable” and a callback function. Our variable is called cookies but you could call it anything. The setCookies function will set the new value of cookies. This is a way to “preserve” some values between the function calls. Normally, variables “disappear” when the function exits but state variables are preserved by React. We pass 0 into useState to set our "initial state". Meaning our cookie clicker count will start at 0.

How to Display Your Current State

If we want to display the current amount of cookies that we have we can use cookies directly:

<p>You have {cookies} cookies!</p>
Enter fullscreen mode Exit fullscreen mode

How to Update State

  <button onClick={() => setCookies(cookies + 1)}>
    Click for Cookie!
  </button>
Enter fullscreen mode Exit fullscreen mode

Thats it!

 1:  import React, { useState } from 'react';
 2:
 3:  function Example() {
 4:    const [cookies, setCookies] = useState(0);
 5:
 6:    return (
 7:      <div>
 8:        <p>You have {cookies} cookies!</p>
 9:        <button onClick={() => setCookies(cookies + 1)}>
10:         Click for Cookie!
11:        </button>
12:      </div>
13:    );
14:  }
Enter fullscreen mode Exit fullscreen mode
  • We import the useState hook from react. This is how we keep track of state in our function.
  • We declare state by calling our useState hook, assign our state variable and callback function a name, and initialize state by passing a 0 indicating that we start with no cookies.
  • Then, when a user clicks the button, we call setCookies with a new value. React will then re-render the Example component, passing the new cookies value to it.

Top comments (1)

Collapse
 
exequielhb profile image
Exequiel Herrera

you could also do the logic of setCookies inside a function outside the return, good contribution