Blog>
Snippets

Implementing Typed UseSelector and UseDispatch Hooks

Show how to define typed versions of useSelector and useDispatch hooks to use in TypeScript projects with React-Redux 9.
import { TypedUseSelectorHook, useSelector as rawUseSelector, useDispatch as rawUseDispatch } from 'react-redux';
import { RootState, AppDispatch } from './store'; // Import your store types here

// Define your typed hooks
export const useSelector: TypedUseSelectorHook<RootState> = rawUseSelector;
export const useDispatch = () => rawUseDispatch<AppDispatch>();
Defines typed versions of useSelector and useDispatch hooks. 'RootState' refers to your root state type, and 'AppDispatch' to your store's dispatch type.
// Usage example for the typed hooks within a component
import React from 'react';
import { useSelector, useDispatch } from './hooks'; // Import your typed hooks here

function MyComponent() {
  const dispatch = useDispatch();
  const someData = useSelector((state) => state.someData);

  return (
    // Your component JSX goes here
  );
}
An example React functional component using the typed hooks to select state and dispatch actions.
/* CSS styles if needed (optional) */
.my-component {
  /* Your CSS styles for the component */
}
Placeholder for the potential CSS styles required for the React component that uses the typed hooks.
<!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>My Typed Hooks Component</title>
    <style>
        /* Include the CSS from the previous step here, if any */
    </style>
</head>
<body>
    <div id="root"></div>
    <script src="path/to/your/compiled/js"></script>
</body>
</html>
HTML template where you would include the React component that utilizes your typed hooks. 'path/to/your/compiled/js' is a placeholder for the actual path to the compiled JavaScript file which includes the React code.