setstate effect in react in javascript

In a functional component in React, you can manage state using the useState hook. To update the state, you can use the setState function returned by the useState hook.

Here's an example of how to use useState and setState:

index.tsx
import React, { useState } from 'react';

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

  function increment() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>Click me</button>
    </div>
  );
}
290 chars
17 lines

In the above example, useState is used to declare a state variable count with an initial value of 0. The setCount function is used to update the state. In the increment function, we call setCount(count + 1) to update the count state.

When the Click me button is clicked, the increment function is called, which in turn calls setCount. This triggers a re-render of the component with the new count value, which is then displayed in the p element.

gistlibby LogSnag