Understanding React Hooks
Tags: javascript, react, beginners
Published: 2021-11-17 06:05:28

One of the great tools that was made available to React developers in the 16.8 release was Hooks.  I'll go into greater detail about what hooks are, why they were developed and how to use them.  Hopefully by the end of this read you will feel more comfortable with the concepts and use-cases of Hooks, allowing you to dive deeper into coding problems, and solving these more complex problems you may run across.


##Why Hooks Were Implemented
Hooks allow developers to use state and other react features without writing classes.  Hooks are able to solve a lot of different problems in React.  You can take stateful logic from components so the logic can be reused and implemented independently.  This allows developers to reuse this logic without changing your component order or hierarchy, making it pretty seamless to share hooks with multiple components.

Another problem that React developers run into is dealing with large, complex components with lots of stateful logic and side effects.  Without hooks related code can be changed together, gets split apart, and completely unrelated code can end up combines in single methods causing lots of bugs and inconsistencies.  With large components like these examples, the stateful logic is all over the place making it hard to refactor or break down components to more manageable sizes.



##What Hooks do
Hooks allow you to split a component into smaller functions within the component based on which code blocks are related.  Hooks also allow developers to use more React features without using classes.  Classes have been known to confuse newer developers and over-complicate code.  Classes are much different then other languages handle classes, unstable syntax and verbose code makes classes a struggle for most developers, especially if they are new to JavaScript.

Hooks embrace functions which is the basis of what components are made of.  This alignment allows developers to learn react and component functionality without getting caught up with complex functional or reactive programming techniques.

Hooks are functions that “hook into” React state and features from inside components.  React provides built in hooks, and allow you to create your own hooks for re-usable stateful behavior between components.


##Examples of popular Hooks:

####State Hook
The useState hook can be called within a component to add local state to it and protect it during application re-renders.  You can call the setState function from within the component or even passed to other components through props, allowing information and code to be transferred and maintained across components.

```
const [count, setCount] = useState(0);

return (
  <div>
    <button onClick={() => setCount(count + 1)}>ClickMe</button>
  </div>
);
```

The above is a simple example of setting your const UseState variables; count, and setCount as well as setting your useState to 0.  What this means is that the variable count is currently set to 0 because we have given useState the value of 0.  the way our anonymous function in our button works is that onClick we will re-set our count to "count + 1" by calling setCount, and passing in the current count variable and adding 1 to it.  This will continually update our count variable because we are re-setting this variable with the setCount function.

####Effect Hook
The useEffect hook adds the ability to perform side effects from within a component.  Side effects can be data fetching, DOM rendering, or actions like subscriptions.  When you call useEffect your basically telling React to run your effect function after sending changes to the DOM.  By default, the effects will be running after every render.  The useEffect also has the ability to clean up after itself by returning a cleanup function.

```
useEffect(()=> {
  fetch('http://localhost:3000')
  .then(res => res.json())
},[])
```

The above code is a prime example of using the Effect Hook.  when we are fetching data we are telling the component to fetch the data after rendering.  React remembers our fetch function and calls on it after performing DOM updates.

####Building your own Hooks
Custom Hooks are more of a convention than a specific feature.  The flexibility of custom hooks allows us to cover a wide range of use-Cases from form handling, timers, and many other options.  Its really up to the developer on how they want to implement custom hooks.

```
import React, { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {
    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}
```

This is an example of custom hook that we have called useFriendStatus.  we can use this hook in other components and the state for each component will be completely independent like so...

```
function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
```
```
function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);

  return (
    <li style={{ color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}
```


It even give us the option to call on a custom Hook twice within the same component, this is because each call to a Hook has a completely isolated state.

####Other Hooks
There are many other hooks that you will come across like useContext, useRef, and useReducer.  For the purpose of this article, I wont go into all of the many hooks that React has implemented.  The number of hooks that are available, and the flexibility that comes with their use is just another example of how great of a tool hooks are.  

##Conclusion
Hooks are part of the new evolvement of code, making code reusable and effective in a  variety of situations.  Technology continues on focusing on problem solving and in some cases addressing problems that have yet to turn up.  the flexibility of hooks allows us as developers to creatively solve problems and situations in new ways.  The greater understanding we have of functionality like hooks will allow us to apply them on a larger scale and discover these new ways to solve problems efficiently. 

[React Documentation](https://reactjs.org/docs/hooks-intro.html)
[MDN Documentation](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state)