Home > Enterprise >  Using Multiple useState hooks
Using Multiple useState hooks

Time:03-08

In React Native project to get input data in form I have used multiple hooks. Is there any better or efficient way to do so?

thanks

const [name, setName] = useState('');
const [surname, setSurname] = useState('');
const [rollNo, setRollNo] = useState('');
const [phone, setPhone] = useState('');
const [email, setEmail] = useState('');
const [address, setAddress] = useState('');

CodePudding user response:

I think this is the correct way to do it. Simple states are a good way to use them. I believe it's better practice to not use '' as initial state but null. So that there is no confusion possible.

CodePudding user response:

You can use useReducer hook or you can also use custom useSetState which which works similar to how this.setState works in class components. It merges object changes into current state.

If the data received from the back-end API is an object containing the user details such as name and email etc etc... then you should not have separate state variables for each and every property. Instead you should save the entire user object in a single state variable. If you need you can de-structure it later like so:

const User = ({ props }) => {
  // good
  const [user, setUser] = useState({});

  const { name, email } = user;

  //bad
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
};
  • Related