react update object in usestate 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: prevstate in usestate

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

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

Tags:

Misc Example