Blog>
Snippets

Using the useSelector Hook to Access State

Showcase using the useSelector hook to access and display state within a component, illustrating how to listen to specific pieces of state.
import React from 'react';
import { useSelector } from 'react-redux';
Imports necessary React and Redux functions.
function UserInfo() {
  // Using useSelector to access the current state of the 'user' slice
  const user = useSelector((state) => state.user);

  // Displaying user information
  return (
    <div>
      <h2>User Information:</h2>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
    </div>
  );
}
Defines a React component that utilizes useSelector to access state.
export default UserInfo;
Exports the UserInfo component for use in other parts of the application.