React.js hooks: useState

useState is a hook that allows you to add state to your functional components. It returns a state value and a function to update that value. The basic syntax of useState is as follows:

import React, { useState } from 'react';

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

  // ...
};

In the example above, state is the current value of the state, and setState is a function to update the state. initialState is the initial value of the state.

To update the state, you can simply call setState with the new value. React will then re-render the component with the updated state. Here’s an example of how to update the state using an event handler:

const handleClick = () => {
  setState(newValue);
};

// ...

<button onClick={handleClick}>Update State</button>

Using useState can greatly simplify your code and make it more concise. It eliminates the need to define a separate class component and manage the state using this.state and this.setState.

By using useState, you can take advantage of the functional component’s simplicity and still have the ability to manage state effectively.

#React #ReactHooks