Top React Hooks — Side Effects and Shared Data

Image for post
Image for post
Photo by Mert Kahveci 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-use

The react-use library is a big library with many handy hooks.

useCustomCompareEffect

We can use the useCustomCompareEffect hook to let us run a callback after comparing the previous and current value our way.

For instance, we can write:

The useCustomCompareEffect hook takes the 3rd argument with a function to compare the previous and current values of the dependency.

createReducer

We can use the createReducer function to create a store that we can use with our component.

For instance, we can write:

We have a reducer function that’s like a redux reducer.

It takes an action object that we can use to set the state.

The createReducer function takes middleware made for Redux and returns the useReducer hook.

The hook takes our reducer and the initial state.

It then returns an array with the state and dispatch variables.

state has the store state.

dispatch lets us dispatch actions to the store.

createReducerContext

The createReducerContext function returns a React context hook that acts like useReducer except that the state is shared between all components in the provider.

For example, we can write:

We used the createReducerContext function to return a SharedCounterProvider .

It takes the reducer and the initial state as the arguments in that order.

This way, we can use the same state across all the components inside the context component.

The useSharedCounter hook lets us get and set the state.

dispatch lets us dispatch our actions to the store.

count has the state.

Conclusion

The react-use library lets us commit side effects in various ways.

It also has hooks to let us share data app-wide.

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