React- Your First Custom Hook

I sure as hell didn’t when I first saw this.

As I mentioned before, see hooks as a tool to separate your logic from your UI.

Keeping that in mind, the onChange() method in the <Form/> component, contains the logic of validating a password.

The <Form/> component knows too much about the way passwords are dealt with.

Whenever you see a component knowing more than it should, it should a sign that you might need to refactor it.

Let’s take the validation logic out of the <Form/> component.

Custom hooks in actionWhen I first saw something like this, it took me around 15 minutes to understand what’s really happening here.

Lucky for you, you’ll gonna understand this in way less.

So here’s what happened:We create a customHook called useSmartPassword() (14)We make our customHook stateful by using React’s useState() hook (15)We define a function, that we will later expose, containing our logic (17)This logic takes in some input from the outside and updates the customHook’s state (21)Finally, we expose the customHooks’s state and our logic function that alters that state (24)Still confused?Whenever you write a custom hook, you must return an array with two elements.

In other languages it’s called a Tuple.

This tuple must contain the currentValue and a function that updates it .

Something like:[currentValue, setCurrentValue] = customHook();The updater function setCurrentValue(), should accept argument(s).

This argument can be the updated state or some other value/function.

If you choose to send some other value/function, you let the updater function update the currentValue according to its own logic.

This is what we have done in the above example.

Remember, whenever you call the updater function setCurrentValue(), you are updating the state of the component.

Just like this.

setState() .

Thus, the component will re-render with our latest state.

The full code can be seen in the following sandbox:Working example using custom hooksConclusionWhat I want you to take away from this article is that hooks let you extract logic and use it across your application if necessary.

Since these hooks let you use the React’s state, you can let React worry about updating the components, while you can write cleaner and scalable code.

As a plus, you don’t have to use classes any more ever again.

 Let’s not say ever again but you get.

.

. More details

Leave a Reply