Introduction to useState and useEffect in React

Introduction to useState and useEffect in React

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks are functions that let you “hook into” React features from function components. React Docs

In the article, we learn about useState and useEffect in functional React components, arguably the most important hooks in React.js.

useState

The useState hook is a functional hook that accepts the reactive value that is always subject to change. The useState provides the same capabilities as this.state in a class component.

Let's take a look at two examples using class components with this.state and functional with useState.

 import React, { useState } from 'react';

  const FirstComponents = () => {
  const [count, setCount] = useState(0);

     return (
      <div>
        <p>You clicked {count} times</p>
         <button onClick={() => setCount(count + 1)}>
         Click me
        </button>
      </div>
    );
  }

Firstly, we import the useState Hook at the top of our component from React Library.

 import React, { useState } from 'react';

We use "array destructuring" from ES6 features to grab two variables count and setCount the value that the hook returns. The first value count takes the initial (0) and the second setCount value represents a function that changes the value and re-renders the component.


 return (
      <div>
        <p>You clicked {count} times</p>
         <button onClick={() => setCount(count + 1)}>
         Click me
        </button>
      </div>
    );
  }

Once the button is clicked, it fires a function setCount which increment by 1 every time it's clicked.

useEffect

The useEffect runs a side-effect function after the first render and every time the state is updated, it will not block the browser from updating the screen. The useEffect function is the same with class based component function of componentDidMount(), componentDidUpdate(), and componentWillUnmount().

The useEffect hook can easily be used alongside the useState hook as shown below:

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

const FirstComponents = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log(`You clicked ${count} times`);
  });

   return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Firstly, we import useEffect from the React library, just like the useState hook(s). useEffect will be called after the page is rendered as shown above, and whenever the state changes the useEffect will re-render.

useEffect dependencies

The useEffect dependency takes an array in comma-delimited variables called the dependency list which is passed in as a second argument that will only run when certain criteria are met.

Firstly, pass in an array that allows the useEffect hook to run only once. As shown below:

import { useState, useEffect } from "react";

const FirstComponents = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log(`You clicked ${count} times`);
  }, []);

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

We added an empty array [] as a second argument to the useEffect as such this will only run once regardless of the number of changes we initiate in the state above.

Now, let us add another name state to the dependency for an effect on that particular state.

import { useState, useEffect } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState("John");

  useEffect(() => {
    console.log(`You have clicked the first button ${count} times`);
  }, [name]);


  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <button onClick={() => setName("Doe")}>Change me</button>
    </div>
  );

Now, useEffect will watch the value name which re-renders anytime fire the function anytime changes are made. The count button will never change again since is not in the dependency but will re-render once we update the name value.

Hooks let us split the code based on what it is doing rather than a lifecycle method name. React will apply every effect used by the component, in the order they were specified. React Docs

Conclusion

We have covered the basics of the useState and useEffect hooks. React hooks provide us with a better way to test our code and an easier way to read and write a cleaner functional approach using the best practice.

If some things didn't quite make a lot of sense to you, check out the hooks API reference, or React FAQ as additional resources.

Understanding these two basic hooks will lay a strong foundation for more complex, and even custom hooks along with their functionalities.

If you’ve found any errors at all, feel free to leave a comment below.

Happy Learning!!