Top React Hooks — State Management

Image for post
Image for post
Photo by Frans Ruiter 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.

Conuse

Conuse is a state management library that lets us share state between components with the Context API.

We can use it by running:

or:

to install it.

Then we can use it by writing:

We have our useCounter ook which returns the count state and the increment function to update the count.

Then we use the createConuse function to create our context provider and the hook to use the context.

We pass our useCounter hook into the object and set that as the value of property.

Then we can use the context with the given name by using the useConuseContext hook with the given string in the Button component

We use the increment function which is the same one we returned in useCounter .

Likewise, the Count component gets the state from the same useConuseContext hook and render the count.

Then in App , we [put everything together with the ConuseProvider wrapping around everything.

ConuseProvider is the context provider, so that’ll be used for sharing the states.

Easy Peasy

Easy Peasy is a package that lets us manage state easily for our React app.

To install it, we run:

to install it.

Then we can use it by writing:

We create a store object with the createStore function.

The todos is the state.

items has the items.

add is an action that we created.

We create an action with the action function.

It has a callback to update the state.

We get the state from the state parameter and do stuff to it.

Then we created the TodoList component.

It uses the useStoreState hook to get the state.

And he useStoreActions get the action we can use.

We pass in a value to add to set the payload parameter's value.

Then in App , we wrap our app with the StoreProvider .

We pass in our store to it so we can get and set its states.

Then we put the TodoList inside it to let us get and set the state.

Image for post
Image for post
Photo by Helena Lopes on Unsplash

Conclusion

Conuse and Easy Peasy are both state management libraries we can use in our React 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