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

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

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 Denunciar

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 Denunciar

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 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