Back

React Hooks Explained!

image

React Hooks Explained

React Hooks are tools that allow you to use state and other React features without writing class components. They're designed to simplify your code and make it easier to share logic across components. Here's a quick overview of what you need to know about React Hooks:

useState

The useState Hook lets you keep track of data in your components. Here's how you use it:

import { useState } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0); 
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>Increment</button>
    </div>
  );
}

useEffect

The useEffect Hook lets you do things after your component renders. For example, you can fetch data, set up subscriptions, or manually change the DOM. Here's how you might fetch data:

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(data => setData(data));
  }, []);

  // ...
}

useContext

The useContext Hook lets you use context in your components. Context is a way to pass data through your component tree without having to pass props down manually at every level.

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

function MyComponent() {
  const theme = useContext(ThemeContext); 
  return <p>The theme is {theme}</p>;
}

useReducer

Think of useReducer as a more powerful version of useState, perfect for when your component's state gets complex. It works well for states that have multiple parts or when the new state depends on the old one.

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

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

useRef

useRef gives you a way to hang onto something (like a DOM element) that doesn't get wiped out when your component re-renders. It's like keeping a sticky note on something you don't want to lose.

const inputEl = useRef(null);

<input ref={inputEl} type="text"/>;

// To get the DOM node:
inputEl.current;

useMemo

useMemo is like a brainy assistant that remembers the result of a heavy-duty function so you don't have to run it again unless absolutely necessary. It helps keep things running smoothly and quickly.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

useCallback

useCallback keeps your functions remembered so they don't get recreated every time your component re-renders. This is especially handy for functions that need to stick around, like event handlers.

const handleClick = useCallback(() => {
  // Something to do here
}, []);

<u>Important note about hook</u>: Don't put Hooks inside loops, conditions, or nested functions. Instead, always use them at the top of your component. This helps React keep track of your Hooks in the right order, which is crucial for things like keeping your component's state consistent across re-renders.