0% found this document useful (0 votes)
2 views4 pages

Web II React Hooks Lesson006

React Hooks, introduced in version 16.8, allow functional components to utilize state and lifecycle features without classes. Key hooks include useState for state management, useEffect for handling side effects, and useContext for accessing context values. Hooks must be called at the top level of a component and not within loops or conditions.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Web II React Hooks Lesson006

React Hooks, introduced in version 16.8, allow functional components to utilize state and lifecycle features without classes. Key hooks include useState for state management, useEffect for handling side effects, and useContext for accessing context values. Hooks must be called at the top level of a component and not within loops or conditions.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

REACT HOOKS

React Hooks are functions that let you "hook into" React state and lifecycle features from
functional components. They were introduced in React 16.8 and provide a more straightforward
way to manage component logic compared to class components. Hooks enable functional
components to manage state, handle side effects, and access other React features without
needing classes.

Basic Hooks

 useState: Enables functional components to manage state.

 useEffect: Handles side effects such as data fetching, subscriptions, or manually


changing the DOM.

 useContext: Allows functional components to access context values.

 useReducer: An alternative to useState for more complex state logic.

 useCallback: Caches a function definition between renders.

 useMemo: Caches the result of a computation between renders.

 useRef: Creates a mutable reference that persists across renders.

Rules of Hooks

 Only call Hooks at the top level of your React function or custom Hook.

 Don't call Hooks inside loops, conditions, or nested functions.

 Call Hooks from within React function components or custom Hooks.

useState – Manages the states

import { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0); // Initial state = 0

return (

<div>
<p>Count: {count}</p>

<button onClick={() => setCount(count + 1)}>Increment</button>

</div>

);

 count: Current state value.

 setCount: Function to update state.

useEffect → Side Effects (API Calls, Subscriptions)

import { useState, useEffect } from 'react';

function DataFetcher() {

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

useEffect(() => {

fetch('https://api.example.com/data')

.then(res => res.json())

.then(data => setData(data));

}, []); // Empty dependency array = runs once on mount

return <div>{data ? data.message : 'Loading...'}</div>;

Runs after render.

 Dependency array ([]) controls when it re-runs:

o [] → Runs once (like componentDidMount).

o [dep] → Runs when dep changes (like componentDidUpdate).

useContext → Access Context Without Prop Drilling


import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemedButton() {

const theme = useContext(ThemeContext); // Reads current theme

return <button className={theme}>Click Me</button>;

useRef → Persist Values Between Renders (Without Re-rendering)

import { useRef } from 'react';

function TextInput() {

const inputRef = useRef(null);

const focusInput = () => {

inputRef.current.focus(); // Directly access DOM element

};

return (

<>

<input ref={inputRef} />

<button onClick={focusInput}>Focus Input</button>

</>

);

}
useReducer → Manage Complex State (Like Redux)

import { useReducer } from 'react';

function reducer(state, action) {

switch (action.type) {

case 'increment':

return { count: state.count + 1 };

default:

return state;

function Counter() {

const [state, dispatch] = useReducer(reducer, { count: 0 });

return (

<div>

<p>Count: {state.count}</p>

<button onClick={() => dispatch({ type: 'increment' })}>+1</button>

</div>

);

You might also like