React useState and useEffect - Easy Guide

Oct. 8, 2021, 12:05 p.m.
React · 5 min read
React useState and useEffect - Easy Guide

Outline

  • Understanding how React hooks work
  • React useState
  • Example: Click Counter
  • Beware of react.fragment
  • How does useState work?
  • React useEffect
  • Practical Example: Fetching an API
  • How does useEffect work?
  • Rule: Only call hooks at the top of your component

 

Introduction

In this article, we are going to be building this counter to understand how React useState works.

React increment counter

 

And you are also going to learn how to use React useEffect hook by using an API and displaying the length of it (this is the number of objects within)!

API length

 

You will learn:

  • useState and how it works
  • useEffect and how it works
  • onClick
  • React fragment: <> </>

Library to be used:

  • Chakra UI

 

Understanding how React hooks work

React Hooks is about bringing a functional state to your components.

In essence, hooks are the replacement of classes.

Here is a definition to read, don't mind if you don't get it at first:

"Hook means 'hook into' React state and lifecycle features from function components"

It is about going from using classes to a more radical but more efficient code.

While you could only add state to your classes, now with hooks you are going to be able to add state into your functions. Before you couldn't do so, it was only an option for classes.

 

React useState

This is the most used hook. Think of all the gigantic apps built with React, its majority contains useState!

As a beginner, you might be wondering how can you apply it to your React toolbox, or maybe you just want to learn how it works.

Example: counter of clicks

import './styles.css'
import { useState } from 'react'
import { Button, ButtonGroup, Flex, Text } from '@chakra-ui/react'


export default function App() {
  const [clicks, setClicks] = useState(0)

  return (
    <>
      <Text fontSize="6xl" textAlign="center">
        {clicks}
      </Text>
      <Flex justifyContent="center">
        <Button colorScheme="teal" mt="10" onClick={() => setClicks(counter + 1)}>
          Increment by 1
        </Button>
      </Flex>
    </>
  )
}

When we click the Button to increment by 1, we do onClick={() => setClicks(counter + 1)}, and so the clicks state increments by 1, and the component re-renders.

 

As a result, the following Text is showing us an updated version of the clicks state.

<Text fontSize="6xl" textAlign="center">

  {clicks}

</Text>

 

Beware of react.fragment

You may not know this, so to make sure, <></> is the equivalent to React.Fragment.

When doing a return() in your React application, you cannot have two children nodes returning, it should only be one.

 

❌ Don't do this: having two children

return (
  <h1>Title</h1>
  <p>Description</p>
  )

 

✅ Instead do this: only one children

return (
  <>
    <h1>Title</h1>
    <p>Description</p>
  </>
)

Once explained this, let's go to the style part.

Chakra UI is a library that provides you with React components, for you to use.

import { Button, ButtonGroup, Flex, Text } from '@chakra-ui/react'

 

return (
  <>
    <Text fontSize="6xl" textAlign="center">
      Some text
    </Text>
    <Flex justifyContent="center">
      <Button colorScheme="teal" mt="10">
        Increment by 1
      </Button>
    </Flex>
  </>
)

Also make sure to have installed every library that Chakra UI requires.

npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4

And wrap the App component with ChakraProvider in the index.js file.

// index.js

import { ChakraProvider } from '@chakra-ui/react'

 

// index.js

ReactDOM.render(
  <ChakraProvider>
    <App />
  </ChakraProvider>,
  rootElement
)

 

Adding useState

First, you should import the useState hook from react.

import { useState } from 'react'

 

Then you have to add the hook itself:

const Component = () => {
  const [clicks, setClicks] = useState(0)
}

Basically, you have the state and the "updater" of that state.

clicks are the state and setClicks is the updater of the clicks state.

Finally, useState(0) takes the initial value of your state and creates it.

In simple words, it initializes your state with the value you pass in the parameters, most commonly the default one, being 0, an empty string, or object.

Reminder! Always create your useState hook at the TOP OF YOUR COMPONENT.

 

How does useState work?

Think of useState as variables. Indeed, useState allows you to have state variables in your functional component.

Another very important note is that "React components automatically re-render whenever there is a change in their state or props".

That's why below when we execute onClick, our state gets updated and the component re-renders with the live state value.

<Text fontSize="6xl" textAlign="center">
  {clicks}
</Text>

<Flex justifyContent="center">
  <Button
    colorScheme="teal"
    mt="10"
    onClick={setClicks(clicks + 1)}
  >
    Increment by 1
  </Button>
</Flex>

 

How to use onClick in React

onclick is not the same as onClick.

The first one is a native JavaScript function (an event listener), and the second one is a "synthetic" React function created by the virtual DOM.

However, both work almost the same.

Here is the main consideration:

 

❌Don't call a function with a parameter, within onclick.

onClick={console.log("clicked")}

 

✅Call it but with a arrow function enclosing it.

onClick={() => console.log("clicked")}

 

React useEffect

If you come from a classes background, then useEffect is the equivalent to:

componentDidMount or componentDidUpdate, it can be both!

There are three steps for our component lifecycle:

1. Component gets mounted

2. Component gets updated

3. Component gets deleted

In apps like Gify or Amazon, what it first wants to do is to show us the information by calling an API.

If we use useEffect for the mounting phase of our component, we could give it a use for fetching an API, right? That is a useful case.

 

Practical example: fetching an API

import './styles.css'
import { useEffect, useState } from 'react'

export default function App() {
  const [data, setData] = useState({})

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos/')
      .then((response) => response.json())
      .then((json) => setData(json))
  }, [data])



  return (
    <div className="App">
      <h1>The length of our API is: {data.length}!</h1>
    </div>
  )
}

 

How useEffect works?

useEffect(() => {})

You basically call a callback that will run asynchronously with your component.

The main thing about useEffect is that you can attach this hook to an event or a change in your state.

That's why useEffect can be componentDidMount and ComponentDidUpdate both at the same time.

 

See the following example below:

useEffect(() => {}, [])

 

Inside the [] would be the thing we want to attach our useEffect execution to.

If you leave it empty, then your useEffect will run every time your component gets mounted.

You might NOT want to leave the [] parameter empty when for example you are using useEffect to fetch a list of products for an e-commerce store.  That's because your useEffect or fetch function would run every time ANY of state is updated, which you would only want when something like your search query changes.

 

Rule to remember: Only call hooks at the top of your component

This is the main rule for you to follow in order to use a react hook:

And don't use them inside if statements or loops.

Have a good coding journey!






Post a Comment
Join the community

0 Comments
0
Written By
alejobravo