Introduction
In this lab, we will explore the useMap hook in React, which creates a stateful Map object and a set of functions to manipulate it. By using this hook, we can easily manage and update key-value pairs in our React components without having to write complex and error-prone logic. This lab will guide you through the implementation of the useMap hook and demonstrate its usage in a sample application.
React useMap Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
- The
useMap()hook creates a statefulMapobject and a set of functions to manipulate it using React hooks. - The
useState()hook initializes theMapstate with theinitialValue. - The
useMemo()hook creates a set of non-mutating actions that manipulate themapstate variable using the state setter to create a newMapevery time. - The
useMap()hook returns an array containing themapstate variable and the createdactions. - The
MyAppcomponent uses theuseMap()hook to initialize the statefulMapobject and provides buttons to add, reset, and remove items from theMap. - The
JSON.stringify()function formats theMapobject into a readable JSON string.
const useMap = (initialValue) => {
const [map, setMap] = React.useState(new Map(initialValue));
const actions = React.useMemo(
() => ({
set: (key, value) =>
setMap((prevMap) => {
const nextMap = new Map(prevMap);
nextMap.set(key, value);
return nextMap;
}),
remove: (key) =>
setMap((prevMap) => {
const nextMap = new Map(prevMap);
nextMap.delete(key);
return nextMap;
}),
clear: () => setMap(new Map())
}),
[setMap]
);
return [map, actions];
};
const MyApp = () => {
const [map, { set, remove, clear }] = useMap([["apples", 10]]);
const handleAdd = () => set(Date.now(), new Date().toJSON());
const handleReset = () => clear();
const handleRemove = () => remove("apples");
return (
<div>
<button
<button
<button disabled={!map.has("apples")}>
Remove apples
</button>
<pre>{JSON.stringify(Object.fromEntries(map), null, 2)}</pre>
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useMap Hook lab. You can practice more labs in LabEx to improve your skills.