Top React Hooks — Portal and Flux

Image for post
Image for post
Photo by Farhan Azam 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.

React Cool Portal

React Cool Portal lets us render our elements outside the usual DOM hierarchy determined by React.

To install it, we run:

or:

Then we can use it by writing:

We called the usePortal hook to return the Portal component.

Then we can render our elements inside the Portal .

By default, the elements inside will be attached to the body.

We can add the ID of the container with the containerId .

If the element with the given ID doesn’t exist, it’ll create it for us.

For instance, we can write:

It also comes with states that we can use to determine whether we show or hide the element in the portal.

For example, we can write:

We used the userPotal hook to get more properties from the returned object.

It returns the show and hide functions to show and hide the portal.

toggle is a function to toggle the portal.

isShow has the state to indicate whether the portal is shown or not.

defaultShow sets whether the portal elements are shown by default or not.

onShow is the function to run something when the portal is shown.

onHide is the function that runs when the portal is hidden.

react-enhanced-reducer-hook

The react-enhanced-reducer-hook library lets us create a centralized data store in our app.

It’s inspired by Redux and works similarly to it.

To install it, we run:

Then we can use it by writing:

We have the useAppReducer hook, which we pass the counterReducer into it.

The hook is created by us by using the useEnhancedReducer hook where we pass the reducer, initial state, and any middleware that we want to run into it.

We return the results of useEnhancedReducer so that we can use it in our component.

The Redux reducer is like any other reducer.

We have the logMiddleware that we can run during state changes.

In App , we get the state and dispatch variables.

state has the current state.

And dispatch has the function to dispatch our actions.

The type is the action type.

Then we get the count state with state.count .

Image for post
Image for post
Photo by Sangga Rima Roman Selia on Unsplash

Conclusion

React Cool Portal lets us create portals without the hassle.

The react-enhanced-reducer-hook library lets us create a centralized data store.

The library is inspired by Redux.

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