React Hooks Tutorial
Key Concepts
- useState: Manages state in functional components.
- useEffect: Manages side effects in functional components.
- useContext: Accesses context in functional components.
- useRef: Manages mutable values that persist across renders.
useState
The useState
hook allows functional components to manage state. It returns an array with two elements: the current state value and a function to update it.
Example:
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> ); }
In this example, the Counter
component uses useState
to manage a count state. Clicking the button updates the state, causing the component to re-render.
useEffect
The useEffect
hook allows functional components to perform side effects such as data fetching, subscriptions, or manually changing the DOM. It runs after every render by default.
Example:
import React, { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <div> <p>Data: {data ? data.message : 'Loading...'}</p> </div> ); }
In this example, the DataFetcher
component uses useEffect
to fetch data from an API when the component mounts. The empty dependency array ensures the effect runs only once.
useContext
The useContext
hook allows functional components to access context, which is useful for sharing state across multiple components without passing props manually.
Example:
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); function ThemedButton() { const theme = useContext(ThemeContext); return ( <button style={{ background: theme === 'dark' ? 'black' : 'white', color: theme === 'dark' ? 'white' : 'black' }}> I am styled by theme context! </button> ); }
In this example, the ThemedButton
component uses useContext
to access the theme context, which determines the button's styling.
useRef
The useRef
hook allows functional components to manage mutable values that persist across renders. It is often used to reference DOM elements or store values that don't trigger re-renders.
Example:
import React, { useRef } from 'react'; function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { inputEl.current.focus(); }; return ( <div> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </div> ); }
In this example, the TextInputWithFocusButton
component uses useRef
to create a reference to the input element. Clicking the button focuses the input element.
Analogies
useState: Think of a thermostat. The temperature is the state, and the thermostat displays it. When you adjust the temperature, the state changes, and the thermostat updates to show the new temperature.
useEffect: Imagine a gardener who plants flowers. The gardener (useEffect) takes care of the flowers (side effects) after planting them. The gardener only needs to water the flowers once they are planted.
useContext: Consider a family sharing a common language. The language (context) is understood by all family members (components) without needing to pass it explicitly between them.
useRef: Picture a bookmark in a book. The bookmark (useRef) keeps its place even as you flip through the pages (renders). The bookmark doesn't change the story (state) but helps you find your place quickly.