Introduction to React Hooks

Introduction to React Hooks

React Hooks are a feature in React that allow you to add state and other React features to functional components. They were introduced in React 16.8 and provide a way to handle state, effects, and other logic in a functional component, instead of writing a class component.

React

React is a popular JavaScript library for building user interfaces. It allows different companies like Scrrum Labs  to build reusable components that can be easily composed to create complex  UI and  manage the state of their applications in a efficient and performant way.

React Hooks are a new feature in React that allow developers to add state and other React features to functional components. Prior to the introduction of Hooks, state and other logic were only possible in class components, which often resulted in complex and verbose code. Hooks provide a way to handle state, effects, and other logic in a functional component, resulting in cleaner, more concise, and reusable code for your project.

useState Hook

useState is a hook in React that allows you to add state to your functional components. It returns an array with two elements: the current state value and a function to update the state. The hook takes an initial state value as an argument and the state can be updated by calling the update function. The state is kept private within the component and only the component that calls useState can access and update it.

import React, { useState } from 'react';

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

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

useEffect Hook

useEffect is a hook in React that allows you to perform side effects in your functional components. Side effects are actions that are performed outside of the render cycle, such as data fetching, manually changing the DOM, or adding/removing event listeners. The useEffect hook takes two arguments: a callback function that contains the side effect code, and a dependency array that determines when the effect should run.

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

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

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

  return <p>Data: {data}</p>;
}

useReducer Hook

useReducer is a hook in React that allows you to manage complex state logic in your functional components. It is similar to useState, but provides more power and structure for managing state updates. The hook takes two arguments: a reducer function that specifies how the state should change in response to actions, and an initial state value. The hook returns an array with two elements: the current state and a dispatch function that allows you to trigger state updates by dispatching actions.

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:
      return state;
  }
}

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

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: 'decrement' })}>
        Decrement
      </button>
    </div>
  );
}

In this example, the useReducer hook is used to manage a counter state, and the reducer function is used to handle actions of type 'increment' and 'decrement'. The component dispatches actions by calling the dispatch function, and the hook takes care of updating the state and re-rendering the component.

useCallback Hook

useCallback is a hook in React that allows you to memoize a function. It returns a memoized version of the function that only changes if one of the dependencies has changed. This is useful for improving the performance of your components by avoiding re-creating functions on every render.

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

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

  const handleClick = useCallback(() => {
    setCount(c => c + 1);
  }, [setCount]);

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

In this example, the useCallback hook is used to memoize the handleClick function, which updates the count state. The dependency array is [setCount], so the memoized function will change only if the setCount function changes, for example, if it is re-created. This helps improve the performance of the component by avoiding unnecessary re-creations of the handleClick function.

useMemo Hook

useMemo is a hook in React that allows you to memoize a value. It returns a memoized value that only re-calculates if one of the dependencies has changed.It is same as useCallBack .the key differenc is useMemo memoizes a value and useCallback memoizes a function.

useRef Hook

useRef is a hook in React that allows you to access the value of a DOM element or a state value without causing a re-render of the component. It returns a mutable object with a current property, which can be used to store a reference to a value.

These are some of the hooks we can use  to add reactivity to our functional components and write clean, reusable code for your applications and projects.

Shape

Drop your comment