npm.io
6.0.1 • Published 1 year ago

use-formatted-message

Licence
ISC
Version
6.0.1
Deps
1
Size
11 kB
Vulns
0
Weekly
0
Stars
4

use-formatted-message

react-intl formatted message hook with use memo

npm version npm downloads node version types

Install

npm install --save use-formatted-message

API

https://christophehurpeau.github.io/use-formatted-message/

Why use this ?

This hook uses useMemo to avoid recall intl.formatMessage at each render, like FormattedMessage component.

Usage

import { defineMessages } from "react-intl";
import useFormattedMessage from "use-formatted-message";

const messages = defineMessages({
  title: {
    id: "some.key.title",
    defaultMessage: "This is the title content",
  },
  titleWithParams: {
    id: "some.key.titleWithParams",
    defaultMessage: "This is the title content, with {count}",
  },
});

function MyComponent({ count = 1 }) {
  const title = useFormattedMessage(messages.title);
  const titleWithParams = useFormattedMessage(
    messages.titleWithParams,
    { count },
    [count],
  );

  return (
    <div>
      <span title={title}>Hello</span>{" "}
      <span title={titleWithParams}>World</span>
    </div>
  );
}