Step 6
Let's revisit the code where we employed useState
:
const [state, setState] = useState({
key: "",
location: "",
which: "",
code: "",
});
The useState
is a React Hook. All Hooks' names start with "use" (that's one of the Rules of Hooks).
The general syntax for using it follows:
const [state, setState] = useState(initialState);
The state
variable always contains the updated (latest) state. To update the state, you must use the setState
function. Only then React will know the state has been updated, and it will re-render the UI.
In class components, the entire state lives in one (potentially large) object, this.state
. However, with the magic of Hooks, you can use as many variables as you wish to hold the state in function components. Indeed, it is common practice to break the app state into its constituents when working with function components.
Update the App
component as follows:
- const [state, setState] = useState({
- key: "",
- location: "",
- which: "",
- code: "",
- });
+ const [key, setKey] = useState("");
+ const [location, setLocation] = useState("");
+ const [which, setWhich] = useState("");
+ const [code, setCode] = useState("");
Subsequently, update the onKeyDown
function:
const onKeyDown = (event) => {
- setState({
- key: event.key,
- location: event.location,
- which: event.which,
- code: event.code,
- });
+ setKey(event.key);
+ setLocation(event.location);
+ setWhich(event.which);
+ setCode(event.code);
};
Finally, delete the following statement:
- const { key, location, which, code } = state;
Save the file and visit the running app. Make sure it works as before.