sachin007
sachin007

Reputation: 85

Using Multiple useState hooks

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('');

Upvotes: 0

Views: 1779

Answers (3)

Parag Diwan
Parag Diwan

Reputation: 159

This may help you. Better use useReducer

import { useReducer } from "react";

const studentInitState = {
  name: null,
  surname: null,
  rollNo: null,
  phone: null,
  email: null
};

function Test(props) {
  const [student, setStudent] = useReducer(
    //--> below line implies. that take old state & update the current state and return the `new state`  this is called a `Reducer` function.
    (student, newDetails) => ({ ...student, ...newDetails }),

    studentInitState
  );


  return (
    <div>
      <button onClick={() => setStudent({ name: "Sachin" })}>Update</button>
      {student.name}
    </div>
  );
}

export default Test;

    

Upvotes: 1

Haresh Samnani
Haresh Samnani

Reputation: 812

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("");
};

Upvotes: 0

Santi
Santi

Reputation: 495

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.

Upvotes: 1

Related Questions