Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 9388  / 5 Years ago, tue, july 9, 2019, 12:00:00

I have a question, if I can use useState generic in React Hooks, just like I can do this in React Components while managing multiple states?


state = {
input1: "",
input2: "",
input3: ""
// .. more states
};

handleChange = (event) => {
const { name, value } = event.target;
this.setState({
[name]: value,
});
};

More From » reactjs

 Answers
2

Yes, with hooks you can manage complex state (without 3rd party library) in three ways, where the main reasoning is managing state ids and their corresponding elements.



  1. Manage a single object with multiple states (notice that an array is an object).

  2. Use useReducer if (1) is too complex.

  3. Use multiple useState for every key-value pair (consider the readability and maintenance of it).


Check out this:


// Ids-values pairs.
const complexStateInitial = {
input1: "",
input2: "",
input3: ""
// .. more states
};

function reducer(state, action) {
return { ...state, [action.type]: action.value };
}

export default function App() {
const [fromUseState, setState] = useState(complexStateInitial);

// handle generic state from useState
const onChangeUseState = (e) => {
const { name, value } = e.target;
setState((prevState) => ({ ...prevState, [name]: value }));
};

const [fromReducer, dispatch] = useReducer(reducer, complexStateInitial);

// handle generic state from useReducer
const onChangeUseReducer = (e) => {
const { name, value } = e.target;
dispatch({ type: name, value });
};

return (
<>
<h3>useState</h3>
<div>
{Object.entries(fromUseState).map(([key, value]) => (
<input
key={key}
name={key}
value={value}
onChange={onChangeUseState}
/>
))}
<pre>{JSON.stringify(fromUseState, null, 2)}</pre>
</div>

<h3>useReducer</h3>
<div>
{Object.entries(fromReducer).map(([key, value]) => (
<input
name={key}
key={key}
value={value}
onChange={onChangeUseReducer}
/>
))}
<pre>{JSON.stringify(fromReducer, null, 2)}</pre>
</div>
</>
);
}

Edit


Notes



  • Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:


setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});

Refer to React Docs.


[#6984] Friday, July 5, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
Tue, Jul 28, 20, 00:00, 4 Years ago
Tue, Dec 10, 19, 00:00, 5 Years ago
Fri, Sep 13, 19, 00:00, 5 Years ago
Tue, Jan 22, 19, 00:00, 5 Years ago
;