Hooked

Anthony Banks
2 min readJun 17, 2021

On the most recent project I worked on in React, I decided to use a few basic React hooks in place of methods I’m used to so here I’ll go over the two hook I implemented; useState and useEffect.

useState:

The useState hook works exactly how it sounds, it lets you “use state”. Specifically useState lets you incorporate state into your functional component. This is extra useful when you’ve already written most of your functional component and later realized it would need state. Even if this isn’t the case, this hook is still quite convenient. Initializing state with useState only takes one line of code. It’ll look something like this.

useState Hook

A variable as an array is formed with 2 arguments, the first argument is a key in state and the second one is a function that will be used to change the value assigned to that key, followed by “= useState()”. And that’s it! State is now initialized on your function component ready to be used. In comparison, here is what state would look like in a class component.

State in a Class Component

useEffect:

This hook is a little more complicated but really it’s nothing new. The useEffect hook is a function that essentially performs the functions componentDidMount() and componentDidUpdate() at the same time in a functional component. This is very useful when you have something in your component you want to make sure stays up to date through any changes to the DOM. Here is the code I used in the project I had worked on.

useEffect Hook

Here the hook will send a ‘get’ request to the backend and set state to the response. The nice thing about useEffect is it is able to run on DOM mounting, updating or both. Here I only needed the fetch to run on mount so I created a second argument as an empty array, this will prevent fetch from running every time the page updates.

These hooks were very helpful in simplifying the processes of React so I am excited to learn more in the future.

--

--