Furkan's Notes

Furkan's Notes

how to: useState

how to: useState

Listen to this article

1. Hook definition

A Hook is a special function that lets you “hook into” React features.

2. useState hook

useState is a Hook that lets you add React state to function components. We’ll learn other Hooks later.

Hooks don’t work inside classes. But you can use them instead of writing classes.

3. Declaring state

For declaring the state we would call useState function which accepts initialState.

import { useState } from "react"

function Counter() {
  // count -> state which initialized by "0"
  // setCount -> function that we can call if we want to change the state
  const [count, setCount] = useState(0);

    // inside of paranthesesis we can show the state
    return <div>{count}</div>
}

4. Updating state

For changing the value of the state, we can call setCount.

import { useState } from "react"

function Counter() {
  // count -> state which initialized by "0"
  // setCount -> function that we can call if we want to change the state
  const [count, setCount] = useState(0);

    // inside of paranthesesis we can show the state
    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => { setCount(count + 1) }}>Increment Counter</button>
        </div>
    )
}
 
Share this