React - useState hook to manage state

0 votes
77 views
added Mar 14 in React by lcjr First Warrant Officer (11,990 points)

In React, useState is a hook, not a variable. Hooks are introduced in React 16.8 as a way to manage state within functional components. Here's how it works:

import React, { useState } from 'react';

function MyComponent() {
  const [item, setItem] = useState({ change_i: 'initial value' }); // Initial state as an object

  // Update the state using setItem
  const handleChange = (newValue) => {
    setItem({ change_i: newValue });
  };

  return (
    <div>
      <input type="text" value={item.change_i} onChange={(e) => handleChange(e.target.value)} />
    </div>
  );
}

 

Explanation:

  1. Import useState: We import useState from the react library.
  2. useState Hook: Inside the component, we call useState with an initial value (here, an object with a change_i property). This returns an array with two elements:
    • item: The current state variable, holding the initial object.
    • setItem: A function used to update the state.
  3. State Update: The handleChange function takes the new value and uses setItem to update the change_i property within the object stored in the item state variable.
  4. JSX: The component renders an input element with the current value of item.change_i and an onChange handler that calls handleChange with the new value from the input.

Variable Naming Convention:

In modern JavaScript and React, it's recommended to use camelCase for variable and property names (e.g., changeI instead of change_i). This improves readability and consistency with common practices.

Key Points:

  • useState is a hook for managing state in functional components.
  • It returns an array with the current state and a function to update it.
  • Use camelCase for variable names.
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...