Blog>
Snippets

Connecting components to the store with useSelector

Illustrate how to read data from the Redux store using the useSelector hook in a functional React component.
import { useSelector } from 'react-redux';

function ExampleComponent() {
  // This hook is used to select a specific piece of state from your redux store
  const exampleData = useSelector((state) => state.exampleData);

  return (
    <div>
      <h1>Data from Redux Store:</h1>
      <p>{exampleData}</p>
    </div>
  );
}
This code defines a functional component in React that uses the useSelector hook from the react-redux library to access the Redux store. The variable 'exampleData' is being retrieved from the store's state (assuming the store has a property called 'exampleData') and is used within the returned JSX template.
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Redux useSelector Example</title>
</head>
<body>
  <div id='root'></div>
  <!-- Here you would include your bundled React scripts that would use the above React component -->
  <script src='/path/to/your/bundled/scripts.js'></script>
</body>
</html>
This is the HTML markup to set up a basic HTML page with a root div where our React application (including our ExampleComponent) would mount using ReactDOM. The script tag at the bottom of the body would be the path to your bundled JavaScript code that contains the React component above.
body {
  font-family: Arial, sans-serif;
}

#root {
  margin: 10px;
  padding: 10px;
  border: 1px solid #000;
}

h1 {
  color: #333;
}

p {
  color: #666;
}
This is a small snippet of CSS that styles the HTML body, root div, and text elements (h1 and p tags) that might be rendered by the React component. It sets the font family, margins, paddings, colors, and borders.