Replace hooks useState inside one object

Viewed 85
  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.

4 Answers

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

You can make a useState like this

const [obj, setObj] = useState({
  country: "",
  City: "",
  Population: "",
  Location: "",
  temp_min: ""
})

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

You can create an object:

const [data, setData] = useState({
  country: '',
  city: '', 
  population: 0, // some number here
  location: '', 
  temp_min: 0, // some number here
});

And then you can get each value like so:

console.log(data.country)
console.log(data.city)
// and so on..
Related