Blog>
Snippets

TypeScript and Redux Hooks

Illustrate the use of Redux hooks, such as useSelector and useDispatch, in a TypeScript context, making sure types are inferred correctly.
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from './store'; // Make sure this path is correct
import { incrementCounter, decrementCounter } from './counterSlice'; // Adjust path and actions accordingly

interface CounterState {
  value: number;
}

// Counter Component using useSelector and useDispatch with TypeScript
class CounterComponent extends React.Component {
  // Use useSelector to get state from the Redux store
  const count = useSelector<RootState, CounterState>(state => state.counter.value);
  // Use useDispatch to create dispatcher functions
  const dispatch = useDispatch();

  return (
    <div>
      <span>Count: {count}</span>
      <button onClick={() => dispatch(incrementCounter())}>Increment</button>
      <button onClick={() => dispatch(decrementCounter())}>Decrement</button>
    </div>
  );
}
This TypeScript code defines a React functional component that uses the useSelector and useDispatch hooks from Redux to interact with the store state. It illustrates selecting the 'count' value from the store using the 'useSelector' hook with a specified type, and dispatching actions using 'useDispatch' to increment and decrement the counter value.
import React from 'react';
import ReactDOM from 'react-dom';

// Import the Redux Provider and the created store
import { Provider } from 'react-redux';
import store from './store';

// Render your app
ReactDOM.render(
  <Provider store={store}>
    <CounterComponent />
  </Provider>,
  document.getElementById('root')
);
This code snippet illustrates how to wrap a React application with the Redux Provider in order to make the Redux store available to all components in the application. This is done at the root of the application so that Redux can be used throughout the app.
body {
  background-color: #f7f7f7;
  font-family: sans-serif;
}

button {
  margin: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  border: 1px solid #ddd;
}

button:hover {
  background-color: #eaeaea;
}
This CSS snippet is a simple styling sheet that can be used for the React components. It defines the base styles for the body and button elements, including the hover state for buttons for a basic interactive visual feedback.