React Hooks

React hooks completetly changed the way we build react applications. It is now a default way to implement the components as it simplifies the code, improves the resuability and remove the limitations of your class component.

In this blog post, we’ll see most common hooks used in react application. Please take a note that, this blog post is not a detailed level explaination of each hooks. This can be used as a quick reference guide of hooks. If you want to understand in detail, I would suggest to refer official documentation on react hooks


1. useState

useState is basically used to manage the state inside your component or you can say local state management.

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

In above code, count represents the current state and setCount is the function to update the value of the count. The complete code example of useState is:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

2. useEffect

useEffect is used to handle the Side Effects. But what is Side Effects ? side effects refer to any operations or actions that occur in a component which affect something outside the component’s scope or state. These actions may cause changes to the environment, like fetching data, updating the DOM directly etc.

And if you have worked on earlier version of react, useEffect also replaces the lifecycle methods of componentDidMount, componentDidUpdate, componentWillUnmount.

It is used for API calls, subscriptions, timers etc..

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

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(interval); // cleanup on unmount
  }, []);

  return <p>Seconds: {seconds}</p>;
}

3. useContext

useContext allows you to consume values from a React Context without prop drilling.

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

const ThemeContext = createContext('light');

function DisplayTheme() {
  const theme = useContext(ThemeContext);
  return <p>Current theme: {theme}</p>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <DisplayTheme />
    </ThemeContext.Provider>
  );
}

4. useReducer

useReducer is used to manage a more complex state

import React, { useReducer } from 'react';

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 Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

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

5. useRef

useRef is used to persist values without Re-render

import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef();

  const focus = () => inputRef.current.focus();

  return (
    <div>
      <input ref={inputRef} placeholder="Type here" />
      <button onClick={focus}>Focus Input</button>
    </div>
  );
}

6. Custom Hooks

import { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

export default useWindowWidth;

use it like:

function App() {
  const width = useWindowWidth();
  return <p>Window width: {width}px</p>;
}

Home ยป React Hooks