ReactJS

all the React hooks with one by one example code:

  1. useState(): This hook 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 that value. Here’s an example:
import React, { useState } from 'react';

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default MyComponent;

In this example, we use the useState() hook to define a count state variable with an initial value of 0. We also define a handleClick() function to update the count value when the button is clicked.

  1. useEffect(): This hook allows you to run side effects in your functional components, such as fetching data from an API or subscribing to events. It takes a function as its first argument, which will be called after every render. Here’s an example:
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  });

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default MyComponent;

In this example, we use the useEffect() hook to update the document title with the current count value after every render.

  1. useContext(): This hook allows you to use a context in your functional components, which can be used to pass data down the component tree without having to pass props manually. Here’s an example:
import React, { useContext } from 'react';

const MyContext = React.createContext();

function MyComponent() {
  const value = useContext(MyContext);

  return <p>Value: {value}</p>;
}

function App() {
  return (
    <MyContext.Provider value="Hello">
      <MyComponent />
    </MyContext.Provider>
  );
}

export default App;

In this example, we use the createContext() function to create a context object, which we then pass down the component tree using the Provider component. In the MyComponent component, we use the useContext() hook to access the current value of the context.

  1. useRef(): This hook allows you to create a reference to a DOM element or to store a mutable value that won’t trigger a re-render when it’s updated. Here’s an example:
import React, { useRef } from 'react';

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

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

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

export default MyComponent;

In this example, we use the useRef() hook to create a reference to the input element, which we then use to focus the input when the button is clicked.

  1. useMemo(): This hook allows you to memoize a value, which means that it will only be computed when its dependencies change. This can help optimize performance when you have expensive calculations or when you need to prevent unnecessary.
import React, { useMemo, useState } from 'react';

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

  const expensiveValue = useMemo(() => {
    console.log('Expensive calculation');

    let result = 0;

    for (let i = 0; i < count * 10000000; i++) {
      result += i;
    }

    return result;
  }, [count]);

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

  return (
    <div>
      <p>Count: {count}</p>
      <p>Expensive value: {expensiveValue}</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default MyComponent;

In this example, we define a count state variable using the useState() hook. We then use the useMemo() hook to memoize the expensiveValue, which is calculated using a for loop. The second argument of useMemo() is an array of dependencies, which in this case is [count], meaning that the value will only be recalculated when the count variable changes.

When we click the button to update the count value, we can see in the console that the expensive calculation is only performed when the count variable changes, and not on every render. This can help optimize performance in cases where you have expensive calculations that don’t need to be updated on every render.

Table of contents

Leave a Comment

Skip to content