Connecting Components with the useSelector Hook
Showcase how to use useSelector hook from React-Redux 9 to read state in a component, replacing the mapStateToProps function.
import React from 'react';
import { useSelector } from 'react-redux';
function UserProfile() {
// Use useSelector hook to access the state
const user = useSelector((state) => state.user);
return (
<div>
<h1>User Profile</h1>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<p>Email: {user.email}</p>
</div>
);
}
export default UserProfile;
This piece of JavaScript code illustrates the usage of the useSelector hook from React-Redux to read state within a React functional component. The UserProfile function component accesses the 'user' slice from the global state using useSelector and displays its properties in the rendered output.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Profile</title>
</head>
<body>
<div id="root"></div>
<!-- Here your React app will be mounted -->
</body>
</html>
This is the HTML template where the React application will mount. The DIV with the id 'root' is the mounting point for the React application.
body {
font-family: 'Arial', sans-serif;
}
div {
margin: 20px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
h1 {
color: #333;
}
p {
color: #666;
}
This CSS provides basic styling for the UserProfile component, making use of font definitions, margins, padding, borders, and colors to present the user information in a more readable format.