React Js

React JS Tutorial Learn React JS, the powerful JavaScript library for building dynamic and interactive user interfaces. This beginner-friendly tutorial covers core concepts like components, state, props, and hooks, with hands-on projects to create responsive web apps. Perfect for aspiring developers looking to master modern front-end development.

React Hooks

25 April 2025 | Category:

React Hooks are a game-changer for developers, allowing you to add state and other React features to functional components without classes. This beginner-friendly tutorial introduces React Hooks through a practical example: building a toggle switch app. Designed to be clear, engaging, and SEO-optimized, this guide is perfect for newcomers to React looking to master Hooks.

What You’ll Learn

  • Basics of React Hooks and their benefits
  • Managing state with the useState Hook
  • Performing side effects with the useEffect Hook
  • Creating a toggle switch component
  • Tips for writing clean Hook-based code

Prerequisites

  • Basic understanding of HTML, CSS, and JavaScript
  • Node.js and npm installed on your system
  • A general idea of React components and JSX

Step 1: Set Up Your React Environment

Let’s start by creating a new React project using Create React App, a quick way to bootstrap a React application.

  1. Open your terminal and run: npx create-react-app react-hooks-toggle cd react-hooks-toggle
  2. Start the development server: npm start

Your browser should open to http://localhost:3000, showing the default React welcome page.

Step 2: What Are React Hooks?

React Hooks, introduced in React 16.8, are special functions that let you use state, lifecycle methods, and other React features in functional components. They make your code simpler and more reusable compared to class components. The two Hooks we’ll focus on are:

  • useState: Adds state to functional components.
  • useEffect: Manages side effects like updating the DOM or logging.

Step 3: Build a Toggle Switch with useState

Let’s create a toggle switch that users can click to turn on or off, using the useState Hook to manage its state.

  1. Replace the contents of src/App.js with: import { useState } from 'react'; import './App.css'; function App() { const [isToggled, setIsToggled] = useState(false); const handleToggle = () => { setIsToggled(!isToggled); }; return ( <div className="App"> <h1>React Hooks Toggle Switch</h1> <p>Status: {isToggled ? 'On' : 'Off'}</p> <button onClick={handleToggle}> {isToggled ? 'Turn Off' : 'Turn On'} </button> </div> ); } export default App;
  2. Save and check the browser. You’ll see a toggle button that switches between “On” and “Off” when clicked, with the status displayed above.

How It Works

  • useState(false) creates a state variable isToggled initialized to false (off) and a setter function setIsToggled.
  • The handleToggle function flips the state using setIsToggled(!isToggled).
  • The button’s text and status message update based on isToggled, showing React’s reactive rendering.

Step 4: Enhance with useEffect

The useEffect Hook lets you perform side effects, such as updating the page or logging state changes. Let’s use it to change the background color of the app based on the toggle state and log the status.

  1. Update src/App.js: import { useState, useEffect } from 'react'; import './App.css'; function App() { const [isToggled, setIsToggled] = useState(false); useEffect(() => { console.log(`Toggle is ${isToggled ? 'On' : 'Off'}`); document.body.style.backgroundColor = isToggled ? '#e0f7fa' : '#ffffff'; return () => { document.body.style.backgroundColor = '#ffffff'; // Reset on cleanup }; }, [isToggled]); const handleToggle = () => { setIsToggled(!isToggled); }; return ( <div className="App"> <h1>React Hooks Toggle Switch</h1> <p>Status: {isToggled ? 'On' : 'Off'}</p> <button onClick={handleToggle}> {isToggled ? 'Turn Off' : 'Turn On'} </button> </div> ); } export default App;
  2. Save and test the app. The background color changes to light blue when the toggle is “On” and resets to white when “Off”. Check the console to see the toggle state logged.

Explanation

  • useEffect runs after every render when isToggled changes (specified in the dependency array [isToggled]).
  • It updates the body’s background color and logs the state.
  • The return statement in useEffect provides cleanup, resetting the background color when the component unmounts or before the next effect runs.

Step 5: Style the Toggle App

To make the app visually appealing, update src/App.css with styles for the layout and button:

.App {
  text-align: center;
  padding: 50px;
  font-family: 'Helvetica', sans-serif;
}

h1 {
  color: #2c3e50;
  margin-bottom: 20px;
}

p {
  font-size: 1.3rem;
  color: #34495e;
  margin-bottom: 30px;
}

button {
  padding: 12px 24px;
  font-size: 1.1rem;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #2980b9;
}

Save and reload the browser. The app now has a polished look with a centered layout, styled text, and a smooth hover effect on the button.

Step 6: Tips for Using React Hooks

  • Adhere to Hook Rules:
    • Call Hooks only at the top level of your component, not inside loops or conditions.
    • Use Hooks only in functional components or custom Hooks.
  • Keep State Simple: Use multiple useState calls for unrelated state variables instead of a single complex object.
  • Optimize Effects: Include a dependency array in useEffect to prevent unnecessary runs, and use cleanup functions for effects like timers.
  • Break Down Components: If your component grows, split it into smaller components, each using Hooks as needed.

Example of a timer effect with cleanup:

useEffect(() => {
  const interval = setInterval(() => console.log('Still running...'), 2000);
  return () => clearInterval(interval);
}, []);

Conclusion

React Hooks make functional components powerful and flexible, letting you manage state and side effects with ease. In this tutorial, you built a toggle switch app using useState to handle the toggle state and useEffect to manage side effects like background color changes. These skills lay the foundation for more complex React projects.