Top React Hooks — Portals and Redux

Image for post
Image for post
Photo by Frank Albrecht on Unsplash

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

useMiddleware

The react-usemiddleware hook lets us create a state with Redux middlewares.

To install it, we run:

or:

Then we can use it by writing:

We have the redux logger that we created with the createLogger function.

We also have the initState with the initial state.

And we created a reducer that’s the usual reducer format.

We pass in the reducer , initState , and middlewares in the useMiddleware hook.

It returns the state with the state from the Redux store and the dispatch function that lets us dispatch an action.

We have the state.count with our count state from the store.

react-useportal

The react-useportal package lets us create portals, which are elements that render outside their usual hierarchy.

To install it, we run:

or:

Then we can use it by writing:

We just return the Portal component by calling the usePortal hook.

Then we can pass in anything in there.

The items will be rendered in the body element.

We can also render the items inside in another element.

For instance, we can write:

to render the items inside Portal in the element with ID hello-world .

We can also use states to render the portal dynamically.

For instance, we can write:

The usePortal hook returns an object with the variables.

The Portal is the portal.

isOpen checks whether the portal is attached or not.

openPortal is a function that set isOpen to true .

closePortal is a function that sets isOpen to false .

We can also press Esc to remove the portal.

This is handy for modals.

Conclusion

The useMiddleware hook lets us use Redux middlewares to our apps.

We can use react-useportal to add portals to our app.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store