3 Essential React Hooks for Beginners

Lavanya Sharma - Aug 18 - - Dev Community

**

Quickly going through description of react hooks which a beginner can start with.

**

useState

useState is the most fundamental hook, allowing you to add state to functional components.

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

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

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

Enter fullscreen mode Exit fullscreen mode

Usage:

  • useState returns an array with two elements: the current state value and a function to update it.

  • The initial state is passed as an argument to useState.

useEffect

  • useEffect lets you perform side effects in function components. It can be used for tasks like data fetching, subscriptions, or manually changing the DOM.
import React, { useEffect, useState } from 'react';

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty dependency array means this runs once, similar to componentDidMount

  return (
    <div>
      {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Usage:

  • useEffect takes a function that will be executed after the component renders.

  • The second argument is an array of dependencies; the effect runs when these dependencies change. An empty array means the effect runs only once.

useContext

  • useContext allows you to use the context API to pass data through the component tree without prop drilling.
import React, { createContext, useContext } from 'react';

// Create Context
const ThemeContext = createContext('light');

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

  return <div>Current theme: {theme}</div>;
}

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

Enter fullscreen mode Exit fullscreen mode

Usage:

  • useContext retrieves the current context value for the given context.

  • The value provided by the closest Context.Provider is used.

.