skip to Main Content

How is react-hot-toast allowing its state to be changed from another components just by exporting the components
in react-hot-toast/src/index.ts
by: export default toast;

Usage in Nextjs14:

=Layout.tsx:

import { Toaster } from "react-hot-toast";

<body>
  {children}
  <Toaster />
</body>

=page.tsx

import { toast } from "react-hot-toast";

<Button
  onClick={() => {
    toast.success("Toast Success");
  }}
>Toast</Button>

no global state!
no prop drilling!
no context api!

2

Answers


  1. Don’t forget that React is just a library based on Javascript. Creating your own state is pretty easy in pure javascript and that’s what react-hot-toast do.
    Have a look at their Github page and you’ll see how it works. Note that there is no .jsx file in the core folder.

    Login or Signup to reply.
  2. Modules can have global state by defining variables with let or const at the top level. Look at this line in React Hot Toast, this is a top level variable in a module, so it is global state, nothing magical. The global state will then be shared between every file that imports "react-hot-toast", as the same file will only be loaded once.

    Note also that the context API is not a workaround for an issue in React, it’s a feature allowing you to avoid global state, while having it still being easily accessible to a large part of your React app. Nothing prevents you from having truly global state (like they do in React Hot Toast), but it has the usual drawbacks of global state. For instance, let’s say that you want to divide your app in two separate panels, each with their own independent toasts, then I would assume this is not easily possible with React Hot Toast because of their use of global state. Using context instead would have made it very easy to implement and it would work out of the box.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search