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

91
Visualizações
Replace hooks useState inside one object
  const [country, setCountry] = useState("");
  const [city, setCity] = useState("");
  const [population, setPopulation] = useState("");
  const [location, setLocation] = useState("");
  const [temp_min, setTmep_min] = useState("");

Hey, anyone has any idea how to replace these hooks useState in an effective way and clean it code like put all of them in an object instead of initialized it with new useState.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use useReducer instead. This would allow you to initialize the state with an object. In addition, you can now use dispatch for all updates, although you'll need to pass it an object with the property you wish to update.

const reducer = (state, update) => ({
  ...state,
  ...update,
});

const [state, dispatch] = useReducer({
  country: '',
  city: '',
  population: '',
  location: '',
  temp_min: ''
});

Examples:

dispatch({ country: 'Spain' }); // setting a country
dispatch({ city: 'Madrid' }); // setting a city
about 4 years ago · Juan Pablo Isaza Relatório

0

You can make a useState like this

const [obj, setObj] = useState({
  country: "",
  City: "",
  Population: "",
  Location: "",
  temp_min: ""
})
about 4 years ago · Juan Pablo Isaza Relatório

0

I implemented the useReducer hook in order to put all these properties in a simple object (which is better for components with complex states) and also using some validations to prevent errors updating state when the component is unmounted, e.g:

const App: React.FC = () => {

  const initialState = {
    name: '',
    password: ''
  };
  const {
    state,
    onUpdateValue, // Update a value from the dictionary
    onClearValue   // Remove a value from the dictionary
    onClear        // Remove all values from the dictionary
  } = useDictionary(initialState);

  const onSubmit = useCallback((event: React.FormEvent) => {
    event.preventDefault();
    console.log('Create User!', state);
    onClear();
  }, [state]);
  
  return (
    <form onSubmit={onSubmit}>
      <label>
        Name:
        <input
          type="text"
          value={state.name}
          onChange={(e) => onUpdateValue('name', e.target?.value)}
        />
      </label>
      <label>
        Password:
        <input
          type="password"
          value={state.password}
          onChange={(e) => onUpdateValue('password', e.target?.value)}
        />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

Link of the repo: https://github.com/proyecto26/use-dictionary

Happy coding! <3

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