Skip to main content

React Hooks: Basic Hooks in React

React Hooks: A Complete Beginner's Guide

React Hooks: A Complete Beginner's Guide

React Hooks are a way to add functionality to functional components in React. Before hooks, we had to use class components to manage state or perform side effects. Hooks make it easier and cleaner to write React code. Let's dive into the basics!

Basic Hooks

1. useState

What is it? useState allows us to create state variables in functional components. Think of state as a "memory" for your component that allows it to "remember" information, like user inputs or the current score in a game.

Real-Life Example: Imagine you're building a simple counter app. The number you see on the screen is the "state" of the app, and you can change it when you click the button.

Code Example:


import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // count is the state, setCount is the function to change it

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

    

2. useEffect

What is it? useEffect is used to handle side effects like fetching data, updating the DOM, or subscribing to events. It's like telling your app to "do something" after it finishes rendering the page.

Real-Life Example: Imagine you're building a weather app. You need to fetch the weather data after the app loads, so you use useEffect to run that logic after rendering.

Code Example:


import React, { useState, useEffect } from 'react';

function Weather() {
  const [weather, setWeather] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/weather')
      .then(response => response.json())
      .then(data => setWeather(data));
  }, []); // The empty array means this effect only runs once, after the first render

  return <div>{weather ? `Today's temperature: ${weather.temp}` : 'Loading...'}</div>;
}

    

3. useContext

What is it? useContext allows you to use values (like themes or user information) from a global context directly in your component. It’s like a "global storage" that your components can access without passing props down manually.

Real-Life Example: Imagine you have an app with a dark mode setting. Instead of passing the dark mode state through each component, you can use useContext to access it globally.

Code 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>;
}

    

Conclusion

These basic hooks—useState, useEffect, and useContext—are essential for building dynamic, interactive apps with React. They let you manage data, perform side effects, and share information across components efficiently.

Comments

Popular posts from this blog

DevOps Best Practices

 # DevOps Best Practices: Your Ultimate Guide to Modern Software Development In today's fast-paced tech world, DevOps isn't just a buzzword – it's a game-changer. Let's dive into the essential practices that can transform your software development process. ![DevOps Lifecycle](https://blogger.googleusercontent.com/img/placeholder.png) ## 🔄 1. Continuous Integration (CI) - The Foundation Think of CI as your code's quality guardian. Every time developers push code, automated tests run to catch issues early. Here's what makes great CI: - Automated builds triggered with every commit - Comprehensive test suites running automatically - Code quality checks integrated into the pipeline - Quick feedback loops to developers **Pro Tip:** Start with simple automated tests and gradually build up your test suite. Remember, it's better to have a few reliable tests than many unreliable ones. ## 🚀 2. Continuous Delivery (CD) - From Code to Customer CD ensures your software ...

Introduction to Cloud Computing: Revolutionizing the Digital Landscape

In today's rapidly evolving digital world, cloud computing stands as a cornerstone of modern technology, transforming how businesses operate and individuals interact with data. Let's dive deep into this fascinating technology that powers our digital future. ## What is Cloud Computing? Imagine having a virtual supercomputer at your fingertips, accessible from anywhere in the world. That's the essence of cloud computing – a technology that delivers computing services such as storage, databases, software, and processing power over the internet, eliminating the need for physical hardware investments. ## The Three Pillars of Cloud Service Models ### Infrastructure as a Service (IaaS) Think of IaaS as renting the digital building blocks of computing. Companies like Amazon Web Services (AWS) and Microsoft Azure provide virtual machines, storage, and networking resources on-demand. This model offers unprecedented flexibility, allowing businesses to scale their infrastructure up or ...

How to Fix "ERESOLVE Unable to Resolve Dependency Tree" Error While Creating a React App

How to Fix Dependency Errors While Creating a React App If you're trying to set up a React app using npx create-react-app and encounter the following error: npm error code ERESOLVE npm error ERESOLVE unable to resolve dependency tree npm error Found: react@19.0.0 npm error Could not resolve dependency: npm error peer react@"^18.0.0" from @testing-library/react@13.4.0 Don't worry! This issue occurs due to dependency conflicts between react , react-dom , and other packages like @testing-library/react . Below are two simple ways to fix this issue. Step 1: Try Fixing It With npm Before switching to Yarn, you can resolve the issue by installing the missing or incompatible dependencies manually. Here's how: After running npx create-react-app my-app , if the error appears, navigate to your project folder: cd my-app Install the missing web-vitals dependency: npm install web-vitals Check for other dependency ...