DEV Community

Cover image for React Hooks
Himanshu Baghel
Himanshu Baghel

Posted on

React Hooks

Hooks are react feature that was introduced in React 16.8 and this allows the developers to use state and react other features in functional components. Before the introduction of Hooks these features available only in class components.Hooks provide a way to manage state, handle side effects, and access lifecycle methods in functional components without the need for class components.

Here are some commonly used Hooks

  1. useState - This hook allow you to add state to functional component and make it statefull function. useState return a state variable and a function to update the state variable.

Syntax-

const [stateVariable,functionToUpdateVariable] = useState(initialValue)

const [isOpen,setIsOpen] = useState(false)
Enter fullscreen mode Exit fullscreen mode

Example-

import React, { useState } from 'react';

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

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
};
export default Counter

Enter fullscreen mode Exit fullscreen mode

OUTPUT-
First output screenshot

Second output screenshot

2) useEffect - This hook is used for handling side effects in functional components, such as fetching data, subscribing to events, or manually changing the DOM. It accepts a callback function and runs it after the component has rendered.

Syntax-

useEffect(callback, dependencies)
useEffect(()=>{},[dependencies])
Enter fullscreen mode Exit fullscreen mode

Example-

import "./App.css";
import React, { useEffect, useState } from "react";

const DataFetch = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data from an API
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        console.log("Data", data);
      });
  }, []);

  return (
    <div>
      <h1>Name: {data[0]?.name}</h1>
      <h1>Name: {data[1]?.name}</h1>
      <h1>Name: {data[2]?.name}</h1>
    </div>
  );
};

export default DataFetch;

Enter fullscreen mode Exit fullscreen mode

OUTPUT-

Output of useEffect

3) useContext- The useContext hook in React allows you to consume a context within a functional component. It provides a way to access the current value of a context created using the createContext() function.

Syntax-

const value = useContext(Context);
Enter fullscreen mode Exit fullscreen mode

Example-

import React, { useContext } from "react";

// Create a context
const MyContext = React.createContext();

// Create a component that provides the context value
const Parent = () => {
  const contextValue = "Hello, My Name is Himanshu Baghel";

  return (
    <MyContext.Provider value={contextValue}>
      <Child />
    </MyContext.Provider>
  );
};

// Create a component that consumes the context
const Child = () => {
  // Consume the context using useContext
  const contextValue = useContext(MyContext);

  return <p>{contextValue}</p>;
};

// Render the parent component
const App = () => {
  return <Parent />;
};

export default App;
Enter fullscreen mode Exit fullscreen mode

OUTPUT-

useContext Output

Thank You

Top comments (2)

Collapse
 
shree675 profile image
Shreetesh M

So, in the third hook, in case we want to define the "Child" component in a different file, can we pass MyContext variable as a prop to the child component and then use the prop inside the child component in the other file in the below manner?

Parent.jsx:

import React from "react";

const MyContext = React.createContext();

const Parent = () => {
  const contextValue = "Hello, My Name is Himanshu Baghel";

  return (
    <MyContext.Provider value={contextValue}>
      <Child context={MyContext} />
    </MyContext.Provider>
  );
};

export default Parent;
Enter fullscreen mode Exit fullscreen mode

Child.jsx:

import React, { useContext } from "react";

const Child = (props) => {
  const contextValue = useContext(props.context);

  return <p>{contextValue}</p>;
};

export default Child;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
himanshubaghel07 profile image
Himanshu Baghel

First of all thanks for your time. and Yes, Your code is correct and also you can take props as array destructuring through this you can access value directly like this .

parent.js

import React from "react";
import Child from "./Child";

const MyContext = React.createContext();

const Parent = () => {
  const contextValue = "I am a frontend Developer";

  return (
    <MyContext.Provider value={contextValue}>
      <Child context={MyContext} />
    </MyContext.Provider>
  );
};

export default Parent;
Enter fullscreen mode Exit fullscreen mode

Child-

import React, { useContext } from "react";

const Child = ({ context }) => {
  const contextValue = useContext(context);

  return <p>{contextValue}</p>;
};

export default Child;

Enter fullscreen mode Exit fullscreen mode

Output-

Props

Thank you