Hooked on React - A Beginner's Guide to React Hooks

When React was first released, class components were the standard way to build complex UIs. However, classes can be cumbersome for some use cases.

Enter React hooks - a way to use React features like state and lifecycle methods without classes.

Hooks provide a more direct API for React concepts you already know. Let’s dive into some commonly used hooks:

Managing State with useState

The useState hook lets components use state without a class:

import { useState } from 'react';

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

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

useState returns the current state value and a function to update it. You can call this function from event handlers and effects.

Using Effects with useEffect

The useEffect hook lets you perform side effects from a component:

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1); 
    }, 1000);
    return () => clearInterval(id);
  }, []);
  
  return <h1>I've rendered {count} times!</h1>
}

Effects are declared inside the useEffect callback. Effects run on mount and unmount.

Sharing State with useContext

useContext provides a way to pass data through the component tree without props:

const UserContext = React.createContext();

function Parent() {
  return (
    <UserContext.Provider value={user}>
      <Child />
    </UserContext.Provider>  
  )
}

function Child() {
  const user = useContext(UserContext);
  
  return <div>{user.name}</div> 
}

Any component can access the context value through useContext.

More Hooks to Explore

There are many more useful hooks - useReducer, useCallback, useMemo, and useRef to name a few. Hooks unlock many great React features without classes.

Give hooks a try to help cut down React boilerplate. Just remember - only call hooks at the top level of components!