React Hooks

Lauren McCoy
3 min readMar 14, 2021

When I first learned React, I learned that there were two different types of components, Class components and Functional components. Class components extend the React library, provides a local state that can be used to store data (for ex: use input from a form), uses the render method and has access to Lifecycle Methods (componentDidMount(), componentDidUnmount(), componentDidUpdate()).

Class Component example

Functional components have a few differences. Functional components don’t require the render method, they don’t have a local state, and they do not have access to lifecycle methods. Functional components (as I learned at the time) were also known as presentational components, as they were meant to show information but not take in any new information. Functional components are basic JavaScript functions.

Functional Component example

Starting with React 16.8, there was a way to add state to functional components and a way to take advantage of some of the benefits provided by componentDidUpdate(), componentDidMount(), and componentDidUnmount() (we still can’t use these exact functions). Hooks allows us to use these features in functional components. Quick note: hooks cannot be used in class components.

There are 2 major hooks: useState() and useEffect(). There is also an option to create custom hooks. Both useState() and useEffect() have to be imported into your functional component. When using the useState() hook, the first argument is the name of your current state, the second argument is the method that will update the current state. These variables are set equal to the useState() method, which is given the initial state value. So below, I’ve created a const variable named title and set its initial value to an empty string. The setTitle variable represents a function that will update our state. There can be multiple instances of useState(). We can create another const, const [author, setAuthor] = useState(‘ ’); . Separating each piece of the state this way allows us to only update the piece of state that we want to update (without overwriting other parts of the state).

useState() hook

The useEffect() hook takes in a function that will be executed after the component has been rendered. useEffect() can be used to gain the behaviors of the lifecycle methods used in class components. Each time props or state changes, the component is re-rendered and your function is executed. For this reason, a second parameter can be passed to place restrictions on the component updating as often. If no specific restrictions exist, pass an empty array as the second argument to avoid potential infinite loops. There can be multiple useEffect() hooks.

useEffect() hook

--

--