Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
How to use just 1 useState() for serveral states

I have a react component that uses several states which are initialized in the same way useState(false), is there a way to combine all these states into a single useState(false)

  const [loading, setLoading] = useState(false);
  const [fields, setFields] = useState(false);
  const [wrongImageType, setWrongImageType] = useState(false);
  const [aboutError, setAboutError] = useState(false);
  const [destinationError, setDestinationError] = useState(false)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do like this

const [states, setStates] = useState({ loading:false, fields:false, wrongImageType:false, aboutError:false, destinationError:false })

Update state like this

setStates((prevState) => ({ ...prevState, loading: true }))
about 4 years ago · Juan Pablo Isaza Report

0

I usually use the useReducer hook. That way, I can just slam properties to some state object and the reducer tidies it all up for me. It also makes it easy when I have to submit an object to an API, I just fling the entire state object to the server. So it's basically, "fetch data from the server, use form inputs to let the user update the values, fling the data back to the server when they click the save button."

import React, {
  useReducer,
  useEffect
} from "react";

const initialState = {
  loading: false,
  fields: false,
  wrongImageType: false,
  aboutError: false,
  destinationError: false
};

const reducer = (prev, cur) => ({ ...prev, ...cur });

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

  useEffect(() => {
    setState({
      loading: true
    });

    // fetch something or do something...

    setState({
      loading: false
    });

  }, []);

  return ({
    state.loading ? <> Loading </> : <>{state.something}</>
  });
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!