Blog>
Snippets

Selecting Theme State in Components

Use the `useSelector` hook to extract and utilize the theme state in React components, illustrating how they reactively update when the theme changes.
import { useSelector } from 'react-redux';

function ThemeComponent() {
  // Using useSelector to get theme state from the Redux store
  const theme = useSelector((state) => state.theme);

  // The component will re-render whenever the theme state updates
  return (
    <div style={{ color: theme.primaryColor, backgroundColor: theme.backgroundColor }}>
      This text is styled according to the current theme!
    </div>
  );
}

export default ThemeComponent;
This code defines a React functional component named ThemeComponent which uses the useSelector hook from react-redux to access the theme state from the Redux store. The component renders a div with text content, styled according to the current theme. The 'color' and 'backgroundColor' style properties are set based on the theme properties. Whenever the theme state changes in the Redux store, ThemeComponent will automatically re-render with the new styles.