Getting Started with React Hooks?: Learn Here With Examples in 2023
Tags: react, reacthook, webdev, javascript
Published: 2023-04-01 12:23:41

React is a popular JavaScript library for building user interfaces. React Hooks is a feature introduced in React 16.8 that enables developers to use state and other React features without writing a class component. Hooks allow developers to write more reusable and concise code.

In this blog, we will explore the different types of React Hooks, how to create our own Hooks, tips and uses for beginners, and a conclusion.

## Different Types of React Hooks

There are several types of Hooks in React, which serve different purposes. Here are the most commonly used Hooks:

## useState Hook

The useState Hook allows us to add state to a functional component. It takes an initial state as a parameter and returns an array of two values: the current state value and a function to update the state. Here's an example:

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
```
In this example, we use the useState Hook to define a count variable and a setCount function. When the button is clicked, the increment function updates the value of count, and the UI is automatically updated.


## useEffect Hook

The useEffect hook is used to perform side effects in a functional component. It takes a function as a parameter, which will be executed after every render. Here's an example:

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

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setTime(time + 1);
    }, 1000);
    return () => clearInterval(intervalId);
  }, [time]);

  return (
    <div>
      <p>Time elapsed: {time} seconds</p>
    </div>
  );
}

```
In this example, we use the useEffect Hook to define a function that runs every second and updates the time variable. We also specify time as a dependency, so that the effect only runs when time changes.


## useContext Hook

The useContext Hook allows us to consume a context value in a functional component. It takes a context object as a parameter and returns the current context value. Here's an example:

```
import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function Header() {
  const theme = useContext(ThemeContext);

  return (
    <div>
      <h1 style={{ color: theme === 'dark' ? 'white' : 'black' }}>
        Welcome to my website!
      </h1>
    </div>
  );
}
```


## useRef Hook

The useRef Hook allows us to create a mutable value that persists for the entire lifetime of the component. It takes an initial value as a parameter and returns a mutable ref object. Here's an example:

```
import React, { useRef } from 'react';

function TextInput() {
  const inputRef = useRef(null);

  function focusInput() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={focusInput}>Focus input</button>
    </div>
  );
}

```
In this example, we use the useRef Hook to create a reference to the text input element. When the button is clicked, the focusInput function is called, which sets the focus to the input element without triggering a re-render.


## useReducer Hook

The useReducer Hook allows us to manage state with a reducer function. It takes a reducer function and an initial state as parameters and returns an array of two values: the current state and a dispatch function. Here's an example:

```
import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>You clicked {state.count} times</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

```
In this example, we use the useReducer Hook to define a reducer function that updates the count property based on the increment and decrement actions. We also define an initialState object with a count property of 0. The Counter component uses the useReducer Hook to manage the state and dispatch actions based on button clicks.

## Creating Custom Hooks

We can also create our own Hooks to reuse code logic across components. Custom Hooks are functions that use one or more built-in Hooks and return a value. Here's an example of a custom Hook that fetches data from an API:

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

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch(url);
      const json = await response.json();
      setData(json);
      setLoading(false);
    }
    fetchData();
  }, [url]);

  return { data, loading };
}

```

We can use this custom Hook in our component like this:

```
import React from 'react';
import useFetch from './useFetch';

function MyComponent() {
  const { data, loading } = useFetch('https://jsonplaceholder.typicode.com/posts/1');

  if (loading) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  );
}

```

## Tips and Uses for Beginners

Here are some tips and uses for beginners to get started with React Hooks:

- Start small and gradually add Hooks to your components.
- Keep your Hooks and state logic separate from your UI code.
- Use the React Developer Tools to inspect and debug your Hooks.
- Use the eslint-plugin-react-hooks package to enforce Hooks rules in your code.
- Here are some common uses for Hooks:
- Manage state and lifecycle events in functional components.
- Share logic across components with custom Hooks.
- Optimize performance with the useMemo and useCallback Hooks.

## Conclusion

React Hooks is a powerful feature that allows developers to write more reusable and concise code. We explored the different types of Hooks, how to create our own Hooks, tips and uses for beginners, and examples of Hooks in action. With React Hooks, we can build complex applications with ease and maintainability.