惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
小众软件
小众软件
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
Security Archives - TechRepublic
Security Archives - TechRepublic
W
WeLiveSecurity
Cloudbric
Cloudbric
博客园 - 司徒正美
美团技术团队
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
PCI Perspectives
PCI Perspectives
宝玉的分享
宝玉的分享
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Last Week in AI
Last Week in AI
S
Schneier on Security
N
News | PayPal Newsroom
B
Blog RSS Feed
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
S
Secure Thoughts
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
L
Lohrmann on Cybersecurity
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tenable Blog
S
Securelist
L
LangChain Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
K
Kaspersky official blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
C
Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
React Tutorial Beginner - `useState` and `useEffect` with Example Code
Amirah Nasih · 2026-05-17 · via DEV Community

React Tutorial Beginner - useState and useEffect with Example Code

In this tutorial, I'm going to give you a step-by-step guide on understanding the main concepts of React which introduce the concept of state and lifecycle in a React component.

State is Memory of a Component

Let's have a brief on what State is.

As a result of an interaction, components frequently need to update what's on the screen. Typing into the form updates the input box, clicking "next" on an image carousel changes the picture displayed and clicking "purchase" adds a product to the shopping cart. Components must "remember" information such as the current input value, the current picture, and the shopping cart. This type of component-specific memory is referred to as a state in React.

Full Tutorial Code

These are the code that you will achieve once you are done with the tutorial. My advice is, to read it until finished and start doing again using the code editor.

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

function Clock() {
  const [time, setTime] = useState(new Date().toString());

  useEffect(() => {
    console.log("component mounted or updated");
    const interval = setInterval(showDate, 1000);

    return () => {
      console.log("cleanup of Interval");
      clearInterval(interval);
    };
  }, [time]);

  function showDate() {
    console.log(new Date().toString('en-GB'));
    setTime(new Date().toString());
  }

  return <h1>{time}</h1>;
}

export default Clock;

Enter fullscreen mode Exit fullscreen mode

First Step

To begin, you can start creating your own react app using the command line or can directly go to CodeSandbox if you want to skip using the command line which is faster. CodeSandbox is an online code editor and prototype tool that speeds up the creation and sharing of web apps where you can directly deploy your app without any hustle.

First, create a new folder inside the src folder named components. Then, create a JavaScript file called Clock.js which in React is the component of Clock.

Create a function Clock Component.

Export this component by typing export default Clock below the function.

function Clock() {}

export default Clock;

Enter fullscreen mode Exit fullscreen mode

Let's create another function in this component, which will be the showDate() function.

After have showDate(), we'll have a <h1> tag to make it large or other tags you prefer and this <h1> will have the date of {new Date().toString()}.

return <h1>{new Date().toString()}</h1>;

Enter fullscreen mode Exit fullscreen mode

Then we call this function with the setInterval(). And have the setInterval as in every one second. Let's call the function first.

function showDate() {
 return <h1>{new Date().toString()}</h1>;
}

setInterval(showDate, 1000);

Enter fullscreen mode Exit fullscreen mode

And this showDate() function will be called in every one second.

Alright, and another thing going do is to have also console.log() above the return method. We console.log() the Date function to see whether its running or not in our console. Like below:

function showDate() {
 console.log(new Date().toString());
 return <h1>{new Date().toString()}</h1>;
}

setInterval(showDate, 1000);

Enter fullscreen mode Exit fullscreen mode

And have to also return a JSX because every component returns a JSX.

Return a JSX below the setInterval() method.

Type return (<div> </div>) as below and let's call the showDate() function inside the <div> JSX.

function Clock() {
 return (
   <div>
     <h1>Hello from Clock component!</h1>
     <div>{showDate()}</div>
   </div>
 );
}

Enter fullscreen mode Exit fullscreen mode

You can also use an empty fragments <> </> to display the JSX like this:

function Clock() {
 return (
  // empty fragment
   <>
     <h1>Hello from Clock component!</h1>
     <div>{showDate()}</div>
   </>
  // empty fragment
 );
}

Enter fullscreen mode Exit fullscreen mode

If you are not seeing anything happen on your screen, go to App.js and import our Clock Component, then use the Clock Component by adding the <Clock />. Like this:

App.js

import Clock from "./components/Clock";

function App() {
  return (
    <>
      <Clock /> {*to use the Clock Component*}
      <p>Hello from App.js</p>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now we will see what is actually happening when we use the Clock component. We see the time and here in the Clock component, you will see that we have a setInterval which is being called every one second.

So, if I go to the inspect element (F12 hotkey) and if I go to console, then in the console you will see that the time is getting updated every second. This is what we will achieve so far:

function Clock() {
  return (
    <div>
      <h1>Hello from Clock component!</h1>
      <div>{showDate()}</div>
    </div>
  )
}

function showDate() {
 console.log(new Date().toString());
 return <h1>{new Date().toString()}</h1>;
}
setInterval(showDate, 1000);

export default Clock;

Enter fullscreen mode Exit fullscreen mode

Time not updated on the screen

But then, on the screen this time not getting updated every second. Only inside the console does it get updated every second.

And that is where we have to use the State.

A state will be a local state of a component. So, whenever a State is changed, a component will re-render and it will render the updated JSX.

So, what we can do is, we need to import a State.

What to do is in the Clock.js Component. Let's have an import React from 'react'; at the top of the Clock() function.

And in order to use a State, there is a hook called useState. To use the useState hook, you need to import the state variable from 'react'. Like below:

import React, { useState } from "react";

Enter fullscreen mode Exit fullscreen mode

Alright, now let's create a constant. To use a State in a function component, you need to create a constant and you have to use an array [] like structure, and then you will have a useState(). Like this:

const [] = useState();

Enter fullscreen mode Exit fullscreen mode

And here you need to give the initial value of your state => useState(initial value). So, my initial value will be the same which is the Date() function.

const [] = useState(new Date().toString())

Enter fullscreen mode Exit fullscreen mode

Put inside useState(), and here I will have the time and I will have a setTime. Whenever you use a useState(), it actually gives you a time variable and it also gives a function to update that variable.

const [time, setTime] = useState(new Date().toString())

Enter fullscreen mode Exit fullscreen mode

So now, we are going to change line return <div>{showDate()}</div>; and have a {time} here and save it. Then start seeing a time on the screen and this is the time.

function Clock() {
 return (
   <div>
     <h1>Hello from Clock component!</h1>
     <div>{time}</div>
   </div>
 );
}

Enter fullscreen mode Exit fullscreen mode

Now, what I'm going to do is I need to update that time.

So whenever this setInterval makes a call to the showDate() in every one second instead of, returning this return <h1>{new Date().toString()}</h1>;

Next, I'm going to update my state.

To Update the State

So want to update my state, I'm going to do a setTime() and this setTime() is going to update the state.

So, let's type setTime(new Date().toString()) and save it.

So, every second my showDate() function is being called function showDate() { and whenever it is called I changed the state variable.

So, you change the state variable with the help of set function; [setTime] = ... This is a set function setTime(new Date().toString()); and as soon as I do a setTime() with a new updated time new Date().toString(), so my state useState() gets changed and whenever the states get change, the component is re-rendered and that's where we will see that the screen is now updating.

We can see now on the screen the time is running every second and also from the console.

If error occurs, make sure that the showDate() is inside the Clock() function. Like below:

import React, { useState } from "react";

function Clock() {
 const [tick, setTick] = useState(new Date().toString());
 setInterval(showDate, 1000);

 return (
   <>
     <h1>Hello from Clock component!</h1>
     <div>{tick}</div>
   </>
 );

 function showDate() {
   console.log(new Date().toString());
   setTick(new Date().toString());
 }
}

export default Clock;

Enter fullscreen mode Exit fullscreen mode

This showDate() function works as updating in every one second, and we use showDate() function inside the Clock function to update the time every one second, to do that, we use state variable which is setTime(new Date().toString()). Earlier in showDate() function we put return <h6>{date}</h6>; because whenever you use a useState(), it actually gives you a time Variable and it also gives a function to update that variable which using set.

Thats why we change from return <h6>{date}</h6>; to setTime(new Date().toString()).

Now on the screen, the time is running every one second and also from the console.

import React, { useState } from "react";

function Clock() {
 const [time, setTime] = useState(new Date().toLocaleTimeString("en-GB"));
 setInterval(updateTime, 1000);

 return (
   <>
     <h2>{time}</h2>
   </>
 );

 // this function used to update the time every one second
 function updateTime() {
   console.log(new Date().toLocaleTimeString("en-GB"));
   setTime(new Date().toLocaleTimeString("en-GB"));
 }
}

export default Clock;

Enter fullscreen mode Exit fullscreen mode

useState Hook

Now, what is this useState() is and what is this [time] and [setTime] is.

Let's have a state, I'm gonna have a constant and now I'm going to create a state variable of name.

So, you will give it as a name, and then whenever you want to update this name, you will update it with the help of a setName function.

const [name, setName]

Enter fullscreen mode Exit fullscreen mode

For example, you can also do the same thing whenever you want to have a flag. Alright, and now you want to update this flag value so you will have a setFlag

const [flag, setFlag]

Enter fullscreen mode Exit fullscreen mode

Alright, so you will use the useState() as const [flag, setFlag] = useState() and then you will set the initial value.

So, my initial value of the flag is true. so let's have a useState(true).

In this way, you will create and use the State.

Lifecycle using the useEffect

Now, what is the lifecycle?

So whenever you have a component, the component also has lifecycles.

So the lifecycles will be that you want to execute something whenever your component is mounted or whenever your component is first time rendered or you want to do something whenever your component is getting updated or whenever your component is destroyed.

💡 Mounting is the phase in which our React component mounts on the DOM (i.e., is created and inserted into the DOM). This method is called just before a component mounts on the DOM or the render method is called. After this method, the component gets mounted.

For example, the Clock component is inserted into the DOM.

We use lifecycle because we want the clock keeps updating. So, need to use the useEffect() function

So, in those cases, you will use a lifecycle.

To use a life cycle method in the function component, we make use of a useEffect hook.

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

Enter fullscreen mode Exit fullscreen mode

So, this way I will use an useEffect hook. And now what I'm going to do here is that I'm going to write a useEffect and this useEffect will have two arguments, useEffect(args1, args2)

The first argument will be a function or a side effect that you want to run and the second argument will be a dependency array. I will use an arrow function as the first argument.

useEffect(() => {})

Enter fullscreen mode Exit fullscreen mode

And the second argument will be the dependency array. So this dependency array will depend on these State variables.

So, now what I'm going to do here is that let's have a console.log() and I'm going to have here a string of "component mounted or updated".

Alright, and remove the dependency array and save it.

 useEffect(() => {
   console.log("component mounted or updated");
 });

Enter fullscreen mode Exit fullscreen mode

I'll save it and now let's go to the inspect element and I will go to the console and here I will just remove this function because we don't want and it's polluting our console. Let's comment out console.log(new Date().toString());

Alright, now I will refresh my page. And you will see that as soon as I refresh my page, My component is mounted and my state is also getting updated.

So, the state is getting updated because this state variable is getting updated.

So, if I don't want that this gets updated every time, what I can do here is that I have a dependency array []

 useEffect(() => {
   console.log("component mounted or updated");
 }, []);

Enter fullscreen mode Exit fullscreen mode

And if I give it a dependency in this array of a state where able then in that case the useEffect() will run only if the state variable changes.

So, what I'm going to do is I'm going to have a flag here:

useEffect( ... ;}, [flag]);

Enter fullscreen mode Exit fullscreen mode

Then, save it, and now will refresh the page.

So, you now will see that even though your time is getting changed in every one second, your useEffect() useEffect( ... ;}, [time]); is not running because your useEffect() is now dependent on another state variable which is a time.

So, that means whenever a time is changed in that case, the useEffect() will run.

So, if the flag is changing from true to false, then you will see that the useEffect will run if I change this flag to true again, then you will see that the useEffect will run.

So this way this is a lifecycle of a component, whenever a component is mounted or whenever a component is updated. you want to run some side effects.

Now, there is a scenario that whenever a component is destroyed you want to run effect of unmounting that whenever the component is unmounted you want to do something.

So, in that case, what we can do is that let's have a constant and gonna have an interval and I will remove/cut the setInterval()

So now I have the interval here and this interval depends on the time.

So, I'm gonna copy this {time} and gonna have the {time} here at useEffect dependency array:

useEffect( ... ;}, [time]);

Enter fullscreen mode Exit fullscreen mode

So, you can see that every time this showDate() function is running my component is getting updated.

So, that's why we see a lot components updated on console logs.

Now, let's assume that you have a subscription to this interval.

Now, you want to clear this subscription whenever your component is unmounted or whenever your component is not visible on your screen.

So what we can do here, inside this useEffect() function is that we can have a clean function. Which will have a return and this will be an arrow function. Alright and here, inside this arrow function, you can do your cleanup.

So, let me have a console.log("cleanup of Interval") and below gonna have the clearInterval method. And let gonna clear this interval. I'm going to add the constant interval into the clearInterval(interval). Like below:

() => {
     console.log("cleanup every one second");
     clearInterval(setInterval(showDate, 1000));
   };

Enter fullscreen mode Exit fullscreen mode

Now see that whenever a component is mounted. the first thing that will happen is the cleanup function will run whenever this component is mounted or whenever a component is unmounted.

useEffect(() => {
  console.log("component keep mounted or updated");

  return () => {
    console.log("cleanup of Interval");
    clearInterval(setInterval(updateTime, 1000));
  };
}, [time]);

Enter fullscreen mode Exit fullscreen mode

Dependency Array

If we remove the dependency, which is [time], in the console will look like this, not update the interval.

component keep mounted or updated
cleanup of Interval
component keep mounted or updated

Enter fullscreen mode Exit fullscreen mode

It is not running because the useEffect() is now dependent on another state variable which is a time.

But if we put dependency array [time], then the console will look like this:

cleanup of Interval
component keep mounted or updated
cleanup of Interval
component keep mounted or updated
cleanup of Interval
component keep mounted or updated
cleanup of Interval
component keep mounted or updated
cleanup of Interval

Enter fullscreen mode Exit fullscreen mode

Then, in that case, the useEffect() will run only if the state variable changes. The second argument is will be the dependency array. So, this dependency array will depend on these State variables.

So, this is how you will do the State and the lifecycle in the React components.

CodeSandbox

Edit state-and-lifecycle-ticking-clock


Share This Tutorial

👉 Please share my posts with the community at daily.dev / social media by adding the article's URL to the feed. By adding my article's URL to the feed, I can share my insights and knowledge with other tech enthusiasts and contribute to the passionate community.

Cheers✨