Conquer the React hooks

Conquer the React hooks

The Things you need to know about React hooks that can help you to conquer the React Hooks concept.

Ā·

8 min read

Every single time you go out to the internet and search for react hooks but you can't understand react hooks efficiently so my friend this blog is for you which can help you to conquer the react hooks concept šŸ˜ƒ.

So enjoy this blog from which you gather information about react hooks.

Here are some basic stuff about React Hooks

React Hooks are a feature introduced in React version 16.8. They allow you to use state and other React features in functional components without the need for class components. This simplifies the syntax and structure of React components.

You see that currently, all the people are using functional components so you need state management that's why you need to learn about React hooks. React Hooks also provide a way to share stateful logic between components, which can further simplify your code and reduce duplication.

Basic React Hooks

Here are some basic and commonly used React hooks.

  1. useState : This hook allows you to use state in functional components. It takes an initial value as an argument and returns an array with two elements: the current state and a function to update the state. Here's an example:
import React, { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
  }

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

ā€¢ In this example, we use the useState hook to initialize a state variable called count 0. We also define a function called handleClick that updates the count variable using the setCount function. Finally, we render the count variable and a button that calls the handleClick function when clicked.

  1. useEffect : This hook allow you to perform side effects in your components. It takes a function as its first argument and an optional array of dependencies as its second argument. Here are some examples :

    1. Example one :
    import React, { useState, useEffect } from 'react';

    function Data() {
      const [data, setData] = useState([]);

      useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts')
          .then(response => response.json())
          .then(data => setData(data));
      }, []);

      return (
        <div>
          {data.map(item => (
            <div key={item.id}>
              <h3>{item.title}</h3>
              <p>{item.body}</p>
            </div>
          ))}
        </div>
      );
    }

    export default Data;

ā€¢ In this example, the useEffect hook is used to fetch data from an API and set it as the state of the component. The second argument of useEffect is an empty array, which means that the effect will only be run once when the component is mounted. In this example, we don't pass a dependency array.

  1. Example two :

     import React, { useEffect } from 'react';
    
     function Title({ title }) {
       useEffect(() => {
         document.title = title;
       }, [title]);
    
       return null;
     }
    
     export default Title;
    

    ā€¢ In this example, the useEffect hook is used to set the document title based on the title prop. The effect is run every time the title prop changes. The component returns null because it doesn't need to render anything. You see that we are passing the title as a dependency array.

  1. useContext : This hook allows you to use context in functional components. It takes a context object as its argument and returns the current value of the context. With the help of this hook, we handle the prop drilling. Here's an example:
import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function ThemeToggle() {
  const theme = useContext(ThemeContext);

  return (
    <button
      style={{ backgroundColor: theme === 'dark' ? '#333' : '#fff', color: theme === 'dark' ? '#fff' : '#333' }}
      onClick={() => {
        theme === 'dark' ? setTheme('light') : setTheme('dark');
      }}
    >
      Toggle theme
    </button>
  );
}

ā€¢ In this example, we create a context object called ThemeContext with a default value of light. We also create a component called ThemeToggle that uses the useContext hook to get the current value of the ThemeContext context. Finally, we render a button that toggles the theme when clicked.

Advanced React Hooks

You see that basic React hooks which used commonly. Now we see some advanced React hooks.

  1. useReducer : The useReducer hook is an alternative to useState that allows you to manage complex state logic in your application. It takes a reducer function and an initial state as arguments and returns the current state and a dispatch function to update the state. Here's an example :

     import React, { useReducer } from 'react';
    
     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, { count: 0 });
    
       return (
         <>
           Count: {state.count}
           <button onClick={() => dispatch({ type: 'increment' })}>+</button>
           <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
         </>
       );
     }
    

    ā€¢ This code is an example of using the useReducer hook in a React component to manage state. The reducer function takes two arguments: the current state and an action object that describes how to update the state. In this case, the action object has a type property that can be either "increment" or "decrement", and the reducer function returns a new state object that either increments or decrements the count property of the previous state.

    ā€¢ In the Counter component, the useReducer hook is used to initialize the state object with a count property set to 0, and to get the dispatch function that is used to update the state by dispatching actions to the reducer. The Count is displayed using the state.count value, and the onClick handlers of the + and - buttons call the dispatch function with the corresponding action type to update the state.

    ā€¢ Overall, this code demonstrates how the useReducer hook can simplify state management in a React component by encapsulating the logic for updating state in a separate function.

  2. useCallback : The useCallback hook is used to memoize functions so that they do not have to be recreated every time a component re-renders. It takes a function and an array of dependencies as arguments and returns a memoized function. Here's an example :

     function MemoizedComponent({ onButtonClick }) {
       const handleClick = useCallback(() => {
         onButtonClick();
       }, [onButtonClick]);
    
       return <button onClick={handleClick}>Click me</button>;
     }
    

    ā€¢ In this example we defines a React functional component called MemoizedComponent that takes a prop called onButtonClick. Within the component, the useCallback hook is used to memorize the handleClick function so that it does not have to be recreated every time the component re-renders. The handleClick function simply calls the onButtonClick function that was passed in as a prop. Finally, the handleClick function is passed as a callback to the onClick event of a button element that is rendered by the component. When the button is clicked, the handleClick function is called, which in turn calls the onButtonClick function.

  3. useMemo : The useMemo hook is used to memoize values so that they do not have to be recalculated every time a component re-renders. It takes a function and an array of dependencies as arguments and returns a memoized value. Here's an example :

     function ExpensiveCalculation({ value }) {
       const result = useMemo(() => {
         // Perform expensive calculation here
         return value * 2;
       }, [value]);
    
       return <div>Result: {result}</div>;
     }
    

    ā€¢ This code defines a component called ExpensiveCalculation that takes a prop called value. Within the component, the useMemo hook is used to perform an expensive calculation (multiplying value by 2) and memoize the result so that it does not need to be recalculated every time the component re-renders. The memoized value is then returned and displayed in the component using the Result: {result} syntax.

    ā€¢ In summary, this component optimizes performance by avoiding unnecessary recalculation of expensive calculations when the component re-renders.

  4. useRef : The useRef hook is used for accessing DOM nodes or storing mutable values in your application. It returns a mutable ref object that can be used to store and update values. The value of the ref persists between renders. Here's an example :

     function MyComponent() {
       const inputRef = useRef(null);
    
       function focusInput() {
         inputRef.current.focus();
       }
    
       return (
         <>
           <input type="text" ref={inputRef} />
           <button onClick={focusInput}>Focus input</button>
         </>
       );
     }
    

    ā€¢ This code defines a functional component called MyComponent that renders an input element and a button. It uses the useRef hook to create a reference to the input element, which is assigned to the inputRef constant.

    ā€¢ The focusInput function is defined inside MyComponent and uses the current property of the inputRef object to access the actual DOM node of the input element and call its focus() method, which sets the focus to the input.

    ā€¢ The button element has an onClick event handler that calls the focusInput function when clicked, which triggers the focus of the input element.

    ā€¢ In summary, this code creates a component that allows the user to focus on an input element by clicking a button using the useRef hook to access the input element and its focus() method.

Conclusion

Using React Hooks can simplify your code and make it easier to reason about, as it encourages a more functional programming style. However, it's important to use them correctly and understand their limitations, as improper use can lead to unexpected behavior or performance issues. You should build customer hooks that can help you to build reusable functions that a React JS software developer can use to add special and unique functionality to the React applications.

Ā