Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

279
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda