What Are ReactJS Hooks at coding filters

What Are ReactJS Hooks?

ReactJS hooks are functions that allow you to “hook into” React’s state and lifecycle features from functional components. Before the introduction of hooks in React 16.8, state and lifecycle methods were only available in class components. Hooks make it possible to manage state, side effects, and other React features in functional components, leading to cleaner and more concise code.

Here’s an overview of the most commonly used hooks:

1. useState

The useState hook allows you to add state to a functional component. It returns an array with two elements: the current state value and a function to update it.

#javascript
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // State variable count initialized to 0
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

2. useEffect

The useEffect hook lets you perform side effects (such as data fetching, subscriptions, or manually changing the DOM) in your component. It runs after every render by default, but you can control when it runs by providing a dependency array.

#javascript #reactjs
import { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => setSeconds(prev => prev + 1), 1000);
    return () => clearInterval(interval); // Cleanup on unmount
  }, []); // Empty array means it only runs once after initial render

  return <div>Timer: {seconds}s</div>;
}

3. useContext

The useContext hook allows you to access the value of a context directly from a functional component. This eliminates the need to use Context.Consumer.

#reactjs #javascript
import { useContext } from 'react';

// Create a context
const ThemeContext = React.createContext('light');

function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return <div>The current theme is {theme}</div>;
}

4. useRef

The useRef hook returns a mutable object (the ref object) whose .current property can hold any value. This is often used for accessing DOM elements directly or for keeping mutable values around without causing re-renders.

#javascript #reactjs
import { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus(); // Focus the input element
  };

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

5. useMemo

The useMemo hook helps optimize performance by memoizing expensive calculations. It only recomputes the result when one of its dependencies has changed.

#reactjs #javascript
import { useMemo } from 'react';

function ExpensiveComputation({ num }) {
  const computedValue = useMemo(() => {
    return num * 2; // Only recompute if num changes
  }, [num]);

  return <div>{computedValue}</div>;
}

6. useCallback

The useCallback hook returns a memoized version of a function that only changes if one of its dependencies changes. It’s often used to avoid unnecessary re-renders when passing callbacks to child components.

#reactjs #javascript
import { useCallback } from 'react';

function Parent() {
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []); // Memoized version of handleClick, changes only if dependencies change

  return <Child onClick={handleClick} />;
}

function Child({ onClick }) {
  return <button onClick={onClick}>Click Me</button>;
}

7. useReducer

The useReducer hook is an alternative to useState, often used when managing more complex state logic (e.g., state that depends on previous state or involves multiple values).

#javascript #reactjs
import { useReducer } from 'react';

function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

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

  return (
    <div>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}

8. useLayoutEffect

useLayoutEffect is similar to useEffect, but it runs synchronously after all DOM mutations. It’s useful when you need to measure DOM elements or apply styles before the browser paints.

#javascript #reactjs
import { useLayoutEffect, useRef } from 'react';

function MeasureComponent() {
  const ref = useRef(null);

  useLayoutEffect(() => {
    const rect = ref.current.getBoundingClientRect();
    console.log('Width:', rect.width);
  }, []);

  return <div ref={ref}>This element's width will be logged</div>;
}

Review:

  • useState: Manages state in functional components.
  • useEffect: Handles side effects (e.g., fetching data, subscriptions).
  • useContext: Accesses context values.
  • useRef: Accesses and interacts with DOM elements or stores mutable values.
  • useMemo: Memoizes values to optimize performance.
  • useCallback: Memoizes functions to prevent unnecessary re-renders.
  • useReducer: Manages more complex state logic.
  • useLayoutEffect: Similar to useEffect, but runs synchronously after DOM updates.

Hooks have revolutionized React development, making functional components more powerful and eliminating the need for class components in many cases.

Using Coding Filters to Streamline Your Development Process!

Incorporating coding filters into your development workflow can streamline processes and reduce redundancy. By filtering out irrelevant data or actions, developers can concentrate on the essential parts of their code, leading to more efficient and less error-prone applications.

Author

  • theaamirlatif

    Frontend Web Dev and UI/UX Engineer, cross-browser, responsive design, user interaction, web accessibility, and client-side optimization in React, WP, Apps Dev.

    View all posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *