Top React Hooks — Shared Data and Default States

Image for post
Image for post
Photo by Mimi Thian 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.

createStateContext

The createStateContext function is a function to create React context hooks.

It acts like useState but the state can be shared with all components in the provider.

For example, we can use it by writing:

We called createStateContext to create the context and hook to use the context.

Then we created 2 components that use the useSharedText hook to get and set the shared state.

The SharedTextProvider is used by wrapping around the components that use the useSharedText hook so we can use the state in both components.

The provider takes the initialValue prop to let us set the initial value of the shared state.

We can write:

to use it.

Then we’ll see ‘abc’ in both components.

useDefault

The useDefault hook returns the default when the state is null or undefined .

For instance, we can write:

to use the useDefault hook.

The first argument is used for the default value.

It’ll be the value of user when we set it to null .

The initialUser is set as the value of user when our component mounts.

When we type in something, then the user will be replaced with what’s typed in.

useGetSet

The useGetSet hook lets us get and set a state value.

For instance, we can write:

The useGetSet hook takes an initial value.

And it returns with the get and set functions to get and set the state data respectively.

Conclusion

The react-use library lets us create a context to share data and get and set data in various ways.

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