Address
304 North Cardinal St.
Dorchester Center, MA 02124

Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM

React Hooks, useState & useEffect in 5 easy steps

react hooks

React Hooks are functions, such as useState and useEffect that allow you to use state and lifecycle methods in a component without writing a class-based component. They were introduced in React 16.8 and have since become a popular way of creating React Components. Hooks enable you to reuse stateful logic across components and make it easier to write reusable and testable code.

1. React Hooks

React Hooks have revolutionized React development by simplifying state and side effect management in functional components. They promote code reusability, enhance component readability, and simplify the development process. With Hooks, developers can create powerful and efficient React applications, leveraging cleaner code and improved component reusability. They have significantly transformed how state and side effects are handled, making components more maintainable and separating concerns effectively. Hooks have brought about a paradigm shift, enabling developers to build robust React applications with ease and efficiency.

  1. Rules of Hooks: React Hooks has some rules that need to be followed. Hooks should always be called at the top level of a component or in other custom hooks, not inside loops, conditions, or nested functions. This ensures that Hooks are called in the same order on every render.
  2. Custom Hooks: Custom Hooks are functions that can be created to encapsulate reusable logic. These functions can use built-in Hooks or other custom Hooks. Custom Hooks allow for code reuse and organization of related logic, making components more modular. To learn How to Create Custom Hooks Follow Create Custom Hooks in React

2. useState Hook

useState is a hook that allows you to add a state to a functional component. It takes an <strong>initial value</strong> as an argument and returns an array containing the current state value and a function to update the state.

  • First of all, Create a React App, in case you don’t know how to create a React app just follow Create a ReactJS project from Scratch
  • Then create a new file named as <strong>useState.js</strong> or whatever you want to and add the following code within that file

useState.js

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>You Clicked the button {count} times.</p>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}

export default Counter;
  • After this add the following code to the already created file <strong>App.js</strong>

App.js

import React from "react";
import Counter from "./useState";

function App() {
  return (
    <div>
      <Counter />
    </div>
  );
}

export default App;
  • Once you have done the above steps, run your app by running the following command in the terminal.
npm start
  • You’ll see such output displayed in the figure below, when you’ll click the button the count will increase to +1, for example, 0 to 1 then 2, 3, and so on.

3. useEffect Hook

useEffect is a hook that allows you to perform side effects in a functional component. It takes a function as an argument and runs it after every render. You can use it to fetch data, add event listeners or update the DOM

  • First of all, Create a React App, in case you don’t know how to create a React app just follow Create a ReactJS project from Scratch
  • Then create a new file named as <strong>useEffect.js</strong> or whatever you want to and add the following code within that file

useEffect.js

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

function Effect() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then((data) => setData(data));
  }, []);

  return (
    <div>
      <ul>
        {data.map((item) => (
          <div key={item.id}>
            <li>{item.title}</li>
          </div>
        ))}
      </ul>
    </div>
  );
}

export default Effect;
  • After this add the following code to the already created file <strong>App.js</strong>

App.js

import React from "react";
import Effect from "./useEffect";

function App() {
  return (
    <div>
      <Effect />
    </div>
  );
}

export default App;
  • Once you have done the above steps, run your app by running the following command in the terminal.
npm start
  • You’ll see such output displayed in the figure below, all the post titles are displayed on the page.

4. Other React Hooks

Some other React Hooks which is used in our React Applications to create multiple features are:

  1. useContext Hook: The useContext Hook enables functional components to access values from a Context created using the Context API. It eliminates the need for nesting multiple levels of components to pass down props.
  2. useRef Hook: The useRef Hook returns a mutable ref object that can hold a value across renders. It is commonly used to access DOM elements or to store mutable values that won’t trigger re-renders.
  3. useMemo Hook: The useMemo Hook allows for memoizing the result of a function. It helps optimize performance by caching expensive calculations and only recomputing when the dependencies change.
  4. useCallback Hook: The useCallback Hook is used to memoize a callback function. It is useful when passing callbacks to child components to prevent unnecessary re-renders of those components.

That’s all to understand useState and useEffect as well as other React hooks. To learn how to create the routes in the ReactJS project, check out “Create routes in ReactJS project“.

If your want to learn more about ReactJS, you can follow all the ReactJS tutorials starting from “Introduction to React” on devcribe.com. Happy Coding!