usestate react object code example

Example 1: update object in react hooks

- Through Input

        const [state, setState] = useState({ fName: "", lName: "" });
        const handleChange = e => {
            const { name, value } = e.target;
            setState(prevState => ({
                ...prevState,
                [name]: value
            }));
        };

        
        
   ***************************

 - Through onSubmit or button click
    
        setState(prevState => ({
            ...prevState,
            fName: 'your updated value here'
         }));

Example 2: react usestate

import React, { useState } from 'react';

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

  return (
    

You clicked {count} times

); }

Example 3: prevstate in usestate

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

setState(prevState => [...prevState, 'somedata'] );

Example 4: react usestate

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      
      
      
    
  );
}

Example 5: simple usestate example

// First: import useState. It's a named export from 'react'
// Or we could skip this step, and write React.useState
import React, { useState } from 'react';
import ReactDOM from 'react-dom';

// This component expects 2 props:
//   text - the text to display
//   maxLength - how many characters to show before "read more"
function LessText({ text, maxLength }) {
  // Create a piece of state, and initialize it to `true`
  // `hidden` will hold the current value of the state,
  // and `setHidden` will let us change it
  const [hidden, setHidden] = useState(true);

  // If the text is short enough, just render it
  if (text.length <= maxLength) {
    return {text};
  }

  // Render the text (shortened or full-length) followed by
  // a link to expand/collapse it.
  // When a link is clicked, update the value of `hidden`,
  // which will trigger a re-render
  return (
    
      {hidden ? `${text.substr(0, maxLength).trim()} ...` : text}
      {hidden ? (
         setHidden(false)}> read more
      ) : (
         setHidden(true)}> read less
      )}
    
  );
}

ReactDOM.render(
  ,
  document.querySelector('#root')
);

Tags: