JavaScript React: Hooks

Francisco Andrade
2 min readAug 13, 2021

JavaScript React has many great built-in tools into its large library. A great example of this, are the different hooks that one can use to update the DOM while creating a React application. Hooks help greatly to make one’s code functionality flow much better and create reader friendly code.

A few hook examples can been seen below in the example code…

With the example shown above, in order to activate the functionality of hooks in a React application they must be imported into the code from the “React” library. A few commonly used hooks in React applications are “useState()” and “useEffect()”.

useState():

UseState is incredibility useful as it allows us to access and update certain values, with a provided default value and granted that it is placed in the correct parent component that will allow values to be passed down to child nodes as well as be called back in order to affect sibling nodes.

  1. Setter functions can be created that allow for new values to be passed into the state variable in order to update its value.
  2. The amount of times useState can be used in a component can range from a single to multiple times.
  3. Creating new functions after state is declared can be used to update state using the previous value.
  4. Values can be passed back and forth between sibling components with callbacks up to the shared parent component that then get passed to the sibling node.

useEffect():

UseEffect is a great tool to update the DOM as data is being fetched to then be posted, patched, deleted, or etc.. Effect accepts a callback function that re-renders the DOM in order to update without having to refresh content.

  1. When a value is changed a second argument is passed to useEffect that will re-render the data being fetched, if no value is changed it will remain the same
  2. UseEffect is typically used when making a HTTP request with a GET method, but it can also be used when using other methods

Hooks in React are an incredible tool to have openly at your fingertips. There are many more hooks that are available for access when creating React applications. These are only a few with brief descriptions to what they are capable of doing. With practice and greater knowledge of hooks creating React applications becomes a simple task to build, to read, and to understand for developers and those reading code in the future.

Sources:

Using the Effect Hook — React (reactjs.org)

Introducing Hooks — React (reactjs.org)

--

--