Resetting the State

While we’ve made it easier for the user to dictate the initial state within the custom hook, they should also be able to reset the state to the initial state at any point in time, i.e., a reset callback they can invoke to reset the state to the initial default state they provided.

This is useful in many different use cases.

Why Reset the State?

Let’s consider a really trivial example.

Assume the terms and conditions content in the user app was so long that they changed the default expanded state to false, i.e., the expandable content isn’t open by default.

Since the content was long, they decided to provide a button towards the end of the write-up. A reader could click to revert the expandable content to the initial closed state for which they may want to close the expandable content and perform some cleanups.

We could provide the user a reset callback for this, right?

Even though this particular example isn’t the most realistic for the reset functionality, in larger applications you can solve the problem using the same method discussed here.

How to Reset State?

So, here comes the solution.

All the reset function should do is set the “expanded” state back to the default provided, i.e., initialExpanded

Here’s a simple implementation:

Get hands-on with 1200+ tech skills courses.