Top React Hooks — Touch and Context

Image for post
Image for post
Photo by Chris Liverani 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.

Melting Pot

Melting Pot has a bunch of hooks that we can use in our React app.

It’s a utility library with many hooks.

To install it, we run:

or:

The useTouch hook lets us watch for the touching of an element.

To use it, we can write:

We use the useTouch hook, which returns an object with the touched and bind properties.

touched indicates whether the item is touched.

bind is an object which we use as props for the element we want to watch for touches.

The useUpdate hook us a replacement of the componentDidUpdate method in React class components.

We can use it by writing:

We can use the useUpdate hook to watch for state updates.

We used the hook with an object passed into it.

action runs when the state is updated.

exit runs when it rerenders.

The useWindowScrollPosition hook lets us watch for the scroll position on our page.

We can use it by writing:

We watch for the scroll position with the hook.

It has the x and y properties to show the scroll position’s x and y coordinates.

Now as we scroll, we’ll see the position update.

The useWindowSize hook lets us watch for the size of the window.

To use it, we write:

The width and height has the width and height of the window.

Constate

The Constate library lets us share data between components by lifting the state to the top with the context API.

We can install it by running:

or:

Then we can write:

to use it.

We created ou own useCounter hook to update the count state.

It returns the state and a function to update it.

Then we use constate to create a context with the hook.

It returns the context provider and a hook to use the context.

Then in Button and Counter , we call useCounterContext to use the state.

It just returns what we return in the useCounter hook.

Then we can use the components together in App without passing props around.

The CounterProvider is the context provider and it has to wrap around everything.

Image for post
Image for post
Photo by Ryan Wallace on Unsplash

Conclusion

Melting Pot has various useful hooks.

Constant lets us share context state in an orderly way.

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