Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda