DEV Community

Cover image for React hooks: useState
Abdullah Furkan Özbek
Abdullah Furkan Özbek

Posted on • Updated on

React hooks: useState

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>
}
Enter fullscreen mode Exit fullscreen mode

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
scriptkavi profile image
ScriptKavi

Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.

Have you started using it?

scriptkavi/hooks

PS: Don't be a late bloomer :P