React JS Hooks


Hooks in React are functions that let you use state and other React features in functional components. They were introduced in React 16.8 to allow functional components to manage state, side effects, context, and more, which were previously only available in class components. Hooks simplify the component logic and promote code reuse.

Common Hooks in React

1. useState

  • Purpose: Adds state to functional components.
  • Usage: It returns a state variable and a function to update that state.
  • 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> ); }

2. useEffect

  • Purpose: Performs side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.
  • Usage: It takes a function that runs after the component renders and an optional dependency array to control when it runs.
  • 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)); }, []); // Empty array means this effect runs only once, similar to componentDidMount return <div>{data ? data.message : 'Loading...'}</div>; }

3. useContext

  • Purpose: Accesses context values in functional components without needing to use the Context Consumer.
  • Usage: It takes a context object and returns the current context value.
  • Example:
    import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); function ThemedComponent() { const theme = useContext(ThemeContext); return <div>The current theme is {theme}</div>; }

4. useReducer

  • Purpose: Manages state in a functional component with a reducer function, which is useful for complex state logic.
  • Usage: It takes a reducer function and an initial state and returns the current state and a dispatch function.
  • Example:
    import React, { useReducer } from 'react'; const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); }

5. useMemo

  • Purpose: Memoizes expensive calculations to avoid recalculating them on every render.
  • Usage: It takes a function and a dependency array, and returns a memoized value.
  • Example:
    import React, { useMemo, useState } from 'react'; function ExpensiveComponent({ value }) { const computeExpensiveValue = (value) => { // Some expensive computation return value * 2; }; const memoizedValue = useMemo(() => computeExpensiveValue(value), [value]); return <div>Computed Value: {memoizedValue}</div>; }

6. useCallback

  • Purpose: Memoizes callback functions to prevent unnecessary re-renders of child components.
  • Usage: It takes a callback function and a dependency array, and returns a memoized version of the callback.
  • Example:
    import React, { useCallback, useState } from 'react'; function Button({ onClick }) { return <button onClick={onClick}>Click me</button>; } function ParentComponent() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { setCount(count + 1); }, [count]); return ( <div> <p>Count: {count}</p> <Button onClick={handleClick} /> </div> ); }

7. useRef

  • Purpose: Provides a way to access DOM elements or store mutable values that do not cause re-renders when updated.
  • Usage: It returns a mutable object with a .current property.
  • Example:
    import React, { useRef } from 'react'; function FocusInput() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); }

Summary

Hooks are a powerful feature in React that allow functional components to use state, side effects, context, and more. They provide a cleaner and more concise way to handle component logic compared to class components, promoting better code organization and reuse. By leveraging hooks like useState, useEffect, and useContext, you can manage component state and side effects effectively while keeping your components functional and easy to understand.