DEV Community

Yongkang Cheng
Yongkang Cheng

Posted on

React: useState

To use useState, first import it with import React, { useState } from 'react';

Basic Syntax

const [varName, setVar] = useState(initial value);
Enter fullscreen mode Exit fullscreen mode

Why do we write like this? Because useState as a function returns two variables. the first one is the var_name, and the second one is the function to change the variable.

"Advanced" Usage

  1. we can get the initial value from a function:
const [varName, setVar] = useState(() => {
  return 1+2-3+4;
});
Enter fullscreen mode Exit fullscreen mode
  1. we can set the indirectly customize the setVar function. For this example, we made the setVar function can only accept the values which are smaller than 10.
const [var, dummy] = useState(0);
const setVar = (value) => {
  if (value > 10) {
    dummy(10);
    return;
  }
  dummy(value);
}
Enter fullscreen mode Exit fullscreen mode

An Example

import React, { useState } from 'react';
import './App.css';


function MyButton({ updateFunc }) {
    return (
    <div>
        <button onClick={updateFunc} className='button'> Click Me</button>
    </div>
    );
}

function App() {
    const [count, setCount] = useState(0);

    return (
    <div className="App">
        <p>This is a counter</p>
        <p>Currently the count is {count}</p>
        <MyButton updateFunc={() => { setCount(count + 1); }}/>
        <MyButton updateFunc={() => { setCount(count - 1); }}/>
    </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)