useState

the useState hook returns an array with two elements, the current state and a function to update it.
Returns a stateful value, and a function to update it.

import React, { useState } from "react"; 

This uses array destructuring to assign names to them.

const [state, setState] = useState(initialState); 
const [count, setCount] = useState(0);

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).
The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.



Lifting State Up

moving the state of an individual component up to its parent
pass it down as a property (or prop) to its children



Controlled Component - Form Input Fields

import React, { useState } from "react"; 
const LoginForm = () => {
   const [email, setEmail] = useState("");
   const [password, setPassword] = useState("");
   const handleSubmit = (event) => {
      event.preventDefault();
   };
  return (
      <form onSubmit = { handleSubmit } >
         <label htmlFor="email">
            Email:
         </label>
         <input type="email"
                id="email"
                value={ email }
                onChange = { (e) => setEmail(e.target.value) }
         />
         <label htmlFor="password">
            Password:
         </label>
         <input type="password"
                id="password"
                value={ password }
                onChange = { (e) => setPassword(e.target.value) }
         />
         <button type="submit">
            Submit
         </button>
      </form>
   );
};


Uncontrolled Component - CheckBox Value

import React, { useRef } from "react"; 
const UncontrolledCheckbox = () => {
   const checkboxRef = useRef(null);
   const handleSubmit = () => {
      console.log(checkboxRef.current.checked);
   };
   return (
      <div>
         <input type="checkbox"
                ref={ checkboxRef }
         </input>
         <button type="button" onClick={ handleSubmit }>
            Submit
         </button
      </div>
   );
};



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext