Home

Manage state using useState hook

React Hooks are introuduced in React v16.8. One of those new hooks is useState hook. In this article I will walk you through a simple example of a react component that uses useState hook.

The general syntax of useState will be:

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

It is recommended that you use const, while you can use let. The reason behind this is that you can't reassign to a constant variable.

You can destructure useState from react package too.

import React,{useState} from 'react'

Example of useState using a simple counter:

The following component renders a simple button which shows the number of times you've clicked the button.

import React from 'react';

export const Counter = () => {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount(count + 1);

  return <button onClick={increment}>Clicked: {count}</button>;
};


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments