[javascript] What is useState() in React?

I am currently learning hooks concept in React and trying to understand below example.

import { useState } from 'react';

function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

The above example increments the counter on the handler function parameter itself. What if I want to modify count value inside event handler function

Consider below example:

setCount = () => {
  //how can I modify count value here. Not sure if I can use setState to modify its value
  //also I want to modify other state values as well here. How can I do that
}

<button onClick={() => setCount()}>
  Click me
</button>

This question is related to javascript reactjs react-native react-hooks react-state

The answer is


React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

and onClick:

<button onClick={setCount}>
    Click me
</button>

Let's quickly explain what is going on in this line:

const [count, setCounter] = useState(0);

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.

update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.


useState is one of build-in react hooks available in 0.16.7 version.

useState should be used only inside functional components. useState is the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.

const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

Please note that useState hook callback for updating the state behaves differently than components this.setState. To show you the difference I prepared two examples.

_x000D_
_x000D_
class UserInfoClass extends React.Component {_x000D_
  state = { firstName: 'John', lastName: 'Doe' };_x000D_
  _x000D_
  render() {_x000D_
    return <div>_x000D_
      <p>userInfo: {JSON.stringify(this.state)}</p>_x000D_
      <button onClick={() => this.setState({ _x000D_
        firstName: 'Jason'_x000D_
      })}>Update name to Jason</button>_x000D_
    </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
// Please note that new object is created when setUserInfo callback is used_x000D_
function UserInfoFunction() {_x000D_
  const [userInfo, setUserInfo] = React.useState({ _x000D_
    firstName: 'John', lastName: 'Doe',_x000D_
  });_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>userInfo: {JSON.stringify(userInfo)}</p>_x000D_
      <button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>_x000D_
    </div>_x000D_
  );_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <div>_x000D_
    <UserInfoClass />_x000D_
    <UserInfoFunction />_x000D_
  </div>_x000D_
, document.querySelector('#app'));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

New object is created when setUserInfo callback is used. Notice we lost lastName key value. To fixed that we could pass function inside useState.

setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })

See example:

_x000D_
_x000D_
// Please note that new object is created when setUserInfo callback is used_x000D_
function UserInfoFunction() {_x000D_
  const [userInfo, setUserInfo] = React.useState({ _x000D_
    firstName: 'John', lastName: 'Doe',_x000D_
  });_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>userInfo: {JSON.stringify(userInfo)}</p>_x000D_
      <button onClick={() => setUserInfo(prevState => ({_x000D_
        ...prevState, firstName: 'Jason' }))}>_x000D_
        Update name to Jason_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
    <UserInfoFunction />_x000D_
, document.querySelector('#app'));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

For more about useState see official documentation.


The syntax of useState hook is straightforward.

const [value, setValue] = useState(defaultValue)

If you are not familiar with this syntax, go here.

I would recommend you reading the documentation.There are excellent explanations with decent amount of examples.

_x000D_
_x000D_
import { useState } from 'react';_x000D_
_x000D_
function Example() {_x000D_
    // Declare a new state variable, which we'll call "count"_x000D_
    const [count, setCount] = useState(0);_x000D_
  _x000D_
  // its up to you how you do it_x000D_
  const buttonClickHandler = e => {_x000D_
   // increment_x000D_
   // setCount(count + 1)_x000D_
   _x000D_
   // decrement_x000D_
   // setCount(count -1)_x000D_
   _x000D_
   // anything_x000D_
   // setCount(0)_x000D_
  }_x000D_
  _x000D_
_x000D_
  return (_x000D_
       <div>_x000D_
          <p>You clicked {count} times</p>_x000D_
         <button onClick={buttonClickHandler}>_x000D_
             Click me_x000D_
         </button>_x000D_
      </div>_x000D_
   );_x000D_
 }
_x000D_
_x000D_
_x000D_


useState() is a React hook. Hooks make possible to use state and mutability inside function components.

While you can't use hooks inside classes you can wrap your class component with a function one and use hooks from it. This is a great tool for migrating components from class to function form. Here is a complete example:

For this example I will use a counter component. This is it:

_x000D_
_x000D_
class Hello extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = { count: props.count };_x000D_
  }_x000D_
  _x000D_
  inc() {_x000D_
    this.setState(prev => ({count: prev.count+1}));_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return <button onClick={() => this.inc()}>{this.state.count}</button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

It is a simple class component with a count state, and state update is done by methods. This is very common pattern in class components. The first thing is to wrap it with a function component with just the same name, that delegate all its properties to the wrapped component. Also you need to render the wrapped component in the function return. Here it is:

_x000D_
_x000D_
function Hello(props) {_x000D_
  class Hello extends React.Component {_x000D_
    constructor(props) {_x000D_
      super(props);_x000D_
      this.state = { count: props.count };_x000D_
    }_x000D_
_x000D_
    inc() {_x000D_
      this.setState(prev => ({count: prev.count+1}));_x000D_
    }_x000D_
_x000D_
    render() {_x000D_
      return <button onClick={() => this.inc()}>{this.state.count}</button>_x000D_
    }_x000D_
  }_x000D_
  return <Hello {...props}/>_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

This is exactly the same component, with the same behavior, same name and same properties. Now lets lift the counting state to the function component. This is how it goes:

_x000D_
_x000D_
function Hello(props) {_x000D_
  const [count, setCount] = React.useState(0);_x000D_
  class Hello extends React.Component {_x000D_
    constructor(props) {_x000D_
      super(props);_x000D_
      this.state = { count: props.count };_x000D_
    }_x000D_
_x000D_
    inc() {_x000D_
      this.setState(prev => ({count: prev.count+1}));_x000D_
    }_x000D_
_x000D_
    render() {_x000D_
      return <button onClick={() => setCount(count+1)}>{count}</button>_x000D_
    }_x000D_
  }_x000D_
  return <Hello {...props}/>_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

Note that the method inc is still there, it wont hurt anybody, in fact is dead code. This is the idea, just keep lifting state up. Once you finished you can remove the class component:

_x000D_
_x000D_
function Hello(props) {_x000D_
  const [count, setCount] = React.useState(0);_x000D_
_x000D_
  return <button onClick={() => setCount(count+1)}>{count}</button>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

While this makes possible to use hooks inside class components, I would not recommend you to do so except if you migrating like I did in this example. Mixing function and class components will make state management a mess. I hope this helps

Best Regards


useState is one of the hooks available in React v16.8.0. It basically lets you turn your otherwise non-stateful/functional components to one that can have its own state.

At the very basic level, it's used this way:

const [isLoading, setLoading] = useState(true);

This then lets you call setLoading passing a boolean value. It's a cool way of having "stateful" functional component.


useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.

The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.


Thanks loelsonk, i did so

_x000D_
_x000D_
const [dataAction, setDataAction] = useState({name: '', description: ''});_x000D_
_x000D_
    const _handleChangeName = (data) => {_x000D_
        if(data.name)_x000D_
            setDataAction( prevState  => ({ ...prevState,   name : data.name }));_x000D_
        if(data.description)_x000D_
            setDataAction( prevState  => ({ ...prevState,   description : data.description }));_x000D_
    };_x000D_
    _x000D_
    ....return (_x000D_
    _x000D_
          <input onChange={(event) => _handleChangeName({name: event.target.value})}/>_x000D_
          <input onChange={(event) => _handleChangeName({description: event.target.value})}/>_x000D_
    )
_x000D_
_x000D_
_x000D_


Hooks are a new feature in React v16.7.0-alpha useState is the “Hook”. useState() set the default value of the any variable and manage in function component(PureComponent functions). ex : const [count, setCount] = useState(0); set the default value of count 0. and u can use setCount to increment or decrement the value. onClick={() => setCount(count + 1)} increment the count value.DOC


useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:

import React, {useState} from react    

function HookCounter {    
  const [count, stateCount]= useState(0)    
    return(    
      <div>     
        <button onClick{( ) => setCount(count+1)}> count{count}</button>    
      </div>    
    )   
 }

useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.


Basically React.useState(0) magically sees that it should return the tuple count and setCount (a method to change count). The parameter useState takes sets the initial value of count.

  const [count, setCount] = React.useState(0);
  const [count2, setCount2] = React.useState(0);

  // increments count by 1 when first button clicked
  function handleClick(){
    setCount(count + 1);
  } 

  // increments count2 by 1 when second button clicked
  function handleClick2(){
    setCount2(count2 + 1);
  } 

  return (
    <div>
      <h2>A React counter made with the useState Hook!</h2>
      <p>You clicked {count} times</p>
      <p>You clicked {count2} times</p>
      <button onClick={handleClick}>
        Click me
      </button> 
      <button onClick={handleClick2}>
        Click me2
      </button>
  );

Based off Enmanuel Duran's example, but shows two counters and writes lambda functions as normal functions, so some people might understand it easier.


useState is a Hook that allows you to have state variables in functional components.

There are two types of components in React: class and functional components.

Class components are ES6 classes that extend from React.Component and can have state and lifecycle methods:

class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
  message: ‘’    
 };
}

componentDidMount() {
/* ... */
 }

render() {
return <div>{this.state.message}</div>;
  }
}

Functional components are functions that just accept arguments as the properties of the component and return valid JSX:

function Message(props) {
  return <div>{props.message}</div>
 }
// Or as an arrow function
const Message = (props) =>  <div>{props.message}</div>

As you can see, there are no state or lifecycle methods.


The answers provided above are good but let me just chip in, useState is async so if your next state is dependent on your previous state it is best you pass useState a callback. See the example below:

import { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      // passing a callback to useState to update count
      <button onClick={() => setCount(count => count + 1)}>
        Click me
      </button>
    </div>
  );
}

This is the recommended way if your new state depends on computation from the old state.


Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with reactjs tag:

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop react hooks useEffect() cleanup for only componentWillUnmount? How to use callback with useState hook in react Push method in React Hooks (useState)? React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component React hooks useState Array Can I set state inside a useEffect hook TypeScript and React - children type? Why do I keep getting Delete 'cr' [prettier/prettier]? How to use componentWillMount() in React Hooks? How to compare oldValues and newValues on React Hooks useEffect? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing Receiving "Attempted import error:" in react app How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once expected assignment or function call: no-unused-expressions ReactJS Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Support for the experimental syntax 'classProperties' isn't currently enabled How can I add raw data body to an axios request? Axios Delete request with body and headers? Enable CORS in fetch api Axios having CORS issue How to center a component in Material-UI and make it responsive? What exactly is the 'react-scripts start' command? how to download file in react js react button onClick redirect page Local package.json exists, but node_modules missing Upgrading React version and it's dependencies by reading package.json What is {this.props.children} and when you should use it? How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps Adding an .env file to React Project React : difference between <Route exact path="/" /> and <Route path="/" /> You should not use <Link> outside a <Router> ReactJS: Maximum update depth exceeded error Functions are not valid as a React child. This may happen if you return a Component instead of from render where is create-react-app webpack config and files? React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

Questions with react-native tag:

How to resolve the error on 'react-native start' React Native Error: ENOSPC: System limit for number of file watchers reached How to update core-js to core-js@3 dependency? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 How can I force component to re-render with hooks in React? What is useState() in React? Getting all documents from one collection in Firestore ReactJS: Maximum update depth exceeded error React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH React Native version mismatch How to use ImageBackground to set background image for screen in react-native How to clear react-native cache? npm install Error: rollbackFailedOptional Hide header in stack navigator React navigation Unable to load script from assets index.android.bundle on windows What are my options for storing data when using React Native? (iOS and Android) React navigation goBack() and update parent state if-else statement inside jsx: ReactJS Open Url in default web browser Module AppRegistry is not registered callable module (calling runApplication) React-Native Button style not work React native ERROR Packager can't listen on port 8081 How to re-render flatlist? Draw horizontal rule in React Native Disable back button in react navigation What is the meaning of 'No bundle URL present' in react-native? How to loop and render elements in React-native? How can I regenerate ios folder in React Native project? Could not connect to React Native development server on Android How to use zIndex in react-native Package signatures do not match the previously installed version Using Axios GET with Authorization Header in React-Native App How to set shadows in React Native for android? Does 'position: absolute' conflict with Flexbox? Unable to Resolve Module in React Native App Axios get in url works but with second parameter as object it doesn't How can I put an icon inside a TextInput in React Native? How do I add an element to array in reducer of React native redux? Unable to connect with remote debugger error: package com.android.annotations does not exist "React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View> Error Running React Native App From Terminal (iOS) How to set image width to be 100% and height to be auto in react native? NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app React Native: Possible unhandled promise rejection How to show SVG file on React Native? how to delete installed library form react native project Run react-native on android emulator

Questions with react-hooks tag:

Invalid hook call. Hooks can only be called inside of the body of a function component React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? react hooks useEffect() cleanup for only componentWillUnmount? How to use callback with useState hook in react Push method in React Hooks (useState)? React Hooks useState() with Object useState set method not reflecting change immediately React hooks useState Array Can I set state inside a useEffect hook How to use componentWillMount() in React Hooks? How to compare oldValues and newValues on React Hooks useEffect? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once

Questions with react-state tag:

What is useState() in React? React js change child component's state from parent component React - how to pass state to another component How do I access store state in React Redux? Understanding React-Redux and mapStateToProps() React - changing an uncontrolled input React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined react change class name on state change Clearing state es6 React Updating state on props change in React Form React this.setState is not a function What is the difference between using constructor vs getInitialState in React / React Native? React: how to update state.item[1] in state using setState? Reactjs setState() with a dynamic key name? What is the difference between state and props in React?