Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. React

Learn React - 10 Code Examples & CST Typing Practice Test

React is a declarative, component-based JavaScript library for building user interfaces, primarily for single-page applications. It allows developers to create reusable UI components and manage application state efficiently.

View all 10 React code examples →
React Counter with useStateReact Theme Toggle with ContextReact Todo List with useStateReact Fetch Data with useEffectReact Form HandlingReact Modal ComponentReact useReducer CounterReact Context Counter ExampleReact Tab ComponentReact LocalStorage Counter

Learn REACT with Real Code Examples

Updated Nov 21, 2025

Explain

React lets you build interactive UIs using a component-based architecture.

It uses a virtual DOM to optimize rendering performance.

Supports declarative programming and one-way data flow.

Core Features

Declarative UI design

State management with useState, useReducer

Side effects handling with useEffect

Context API for global state

Integration with routing libraries (React Router)

Basic Concepts Overview

JSX: HTML-like syntax in JavaScript

Components: functional and class-based

Props: data passed from parent to child

State: local component data

Hooks: useState, useEffect, useContext, useReducer

Project Structure

src/index.js - entry point

src/App.js - main component

src/components/ - reusable UI components

src/assets/ - images, fonts, styles

public/ - static files and HTML template

Building Workflow

Create reusable components

Manage state using hooks or Context

Handle events using synthetic events

Update UI declaratively through state changes

Use routing libraries for SPA navigation

Difficulty Use Cases

Beginner: static UI with components

Intermediate: dynamic state and event handling

Advanced: Hooks, context, and lifecycle methods

Expert: Integration with Redux, Router, API fetching

Community: contributing to open-source React libraries

Comparisons

More declarative than plain JavaScript DOM manipulation

Component-based unlike jQuery

Faster UI updates via virtual DOM

Not a full framework, flexible with other libraries

Easier maintenance for large-scale apps

Versioning Timeline

2013 - Initial release by Facebook

2015 - React 0.14 functional components

2016 - React Fiber architecture announced

2018 - Hooks introduced

2025 - Continuous improvements with React 21+ features

Glossary

JSX: JavaScript XML syntax

Component: reusable UI building block

State: local component data

Props: data passed to components

Hook: function to use React features in functional components

Installation Setup

Install Node.js and npm/yarn

Create project using Create React App or Vite

Install React and ReactDOM via npm

Use JSX syntax in `.js` or `.jsx` files

Run project using development server (npm start)

Environment Setup

Install Node.js and npm

VS Code or preferred IDE

Browser for testing

React DevTools extension

Optional: TypeScript setup

Config Files

package.json - project dependencies

webpack.config.js - bundler config

.babelrc - transpiler config

tsconfig.json - for TypeScript React

public/index.html - main HTML template

Cli Commands

npx create-react-app my-app - initialize project

npm start - run development server

npm run build - create production build

npm test - run tests

npm install package - add dependencies

Internationalization

React-Intl or i18next libraries

Dynamic language switching

RTL and LTR support

Locale-based formatting for dates/numbers

Translation JSON files or APIs

Accessibility

Use semantic HTML

Focus management and keyboard navigation

ARIA attributes for dynamic components

Screen reader support

Avoid visual-only cues

Ui Styling

CSS Modules or Styled Components

Inline styles or CSS-in-JS

Theming via context or libraries

Responsive layouts with CSS/JSX

Animations with React Transition Group or Framer Motion

State Management

Local state with useState

Side effects with useEffect

Global state with Context API

Advanced state with Redux/MobX

Persist state with localStorage/sessionStorage

Data Management

Use props for data passing

Fetch APIs with fetch/axios

Use useReducer for complex state

Cache data to optimize performance

Use Context/Redux for app-wide state

Architecture

Component-based structure

Virtual DOM diffing and reconciliation

One-way data flow from parent to child

Unidirectional props for data passing

Hooks and context for state management

Rendering Model

Virtual DOM diffing

Efficient reconciliation

Component tree rendering

State and props trigger re-renders

Batched updates for performance

Architectural Patterns

Component-based architecture

Single-page application pattern

Hooks for state and side effects

Context API for global state

Integration with Redux/MobX for complex state

Real World Architectures

Single-page apps with React Router

Dashboards with dynamic charts

E-commerce front-ends

React Native mobile apps

Component libraries and design systems

Design Principles

Declarative UI

Component reusability

Unidirectional data flow

Virtual DOM optimization

Composition over inheritance

Scalability Guide

Split UI into reusable components

Lazy-load components

Use code-splitting and chunking

Adopt TypeScript for type safety

Integrate automated testing and CI/CD

Migration Guide

Update class components to functional components with hooks

Replace deprecated lifecycle methods

Use React Router v6+ syntax

Modularize large components

Refactor state management to hooks/context/Redux

Performance Notes

Use React.memo to prevent unnecessary re-renders

Avoid inline functions in render when possible

Lazy-load components with React.lazy

Use key prop correctly in lists

Optimize context usage to prevent excessive re-renders

Security Notes

Escape user input to prevent XSS

Do not use `dangerouslySetInnerHTML` with untrusted content

Use HTTPS for API calls

Validate props to prevent unexpected errors

Follow secure coding practices for state management

Monitoring Analytics

Browser dev tools for performance

React Profiler for component rendering

Error tracking with Sentry

Analytics integration for user tracking

Monitor bundle size and load times

Code Quality

ESLint and Prettier for consistency

Unit tests with Jest and RTL

Integration tests for component flows

Type checking with TypeScript or PropTypes

Code reviews and modular design

Practical Examples

Dynamic to-do list app

Interactive forms with validation

SPA with multiple pages and navigation

Dashboard with charts and data fetching

Reusable component library

Troubleshooting

Check console for warnings or errors

Ensure proper import of React and components

Validate JSX syntax

Check state updates and rendering

Verify props and event handlers are correctly passed

Testing Guide

Unit testing components with Jest

Integration testing with React Testing Library

Check rendering and props

Test user interactions and events

Ensure accessibility with a11y testing tools

Deployment Options

Build optimized bundle with `npm run build`

Deploy static bundle to Netlify, Vercel, or GitHub Pages

Integrate with server-side rendering frameworks like Next.js

Use CDNs for assets

Automate deployment with CI/CD pipelines

Tools Ecosystem

Create React App or Vite for project bootstrapping

React Developer Tools extension

npm or yarn package managers

Testing tools: Jest, React Testing Library

Build tools: Webpack, Babel

Integrations

HTML for root structure

CSS or CSS-in-JS for styling

State management libraries: Redux, MobX

Routing: React Router

Backend APIs via fetch or Axios

Productivity Tips

Use reusable components

Leverage hooks effectively

Optimize renders with memoization

Use context and state wisely

Automate repetitive tasks and testing

Challenges

Build a dynamic to-do list

Create a multi-page SPA

Develop a real-time chat UI

Integrate API data with React components

Optimize rendering performance

Learning Path

Learn JSX and component structure

Understand props and state

Practice hooks (useState, useEffect)

Learn routing and SPA patterns

Integrate with state management and APIs

Skill Improvement Plan

Week 1: JSX and functional components

Week 2: State and props

Week 3: Event handling and forms

Week 4: Hooks and side effects

Week 5: Routing, context, and advanced patterns

Interview Questions

What is the difference between class and functional components?

Explain React hooks and use cases

What is the virtual DOM?

How do props and state differ?

Explain the concept of lifting state up

Cheat Sheet

<MyComponent /> - renders component

useState(initialValue) - manage state

useEffect(fn, [deps]) - side effects

props - pass data from parent

React Router: <Route path='/'> for routing

Books

The Road to React by Robin Wieruch

Learning React by Alex Banks & Eve Porcello

React Up & Running by Stoyan Stefanov

Fullstack React by Accomazzo et al.

React Design Patterns and Best Practices by Michele Bertoli

Tutorials

React official tutorial

FreeCodeCamp React course

Codecademy React lessons

Scrimba React courses

Fullstackopen React modules

Official Docs

https://reactjs.org/docs/getting-started.html

https://react.dev

https://reactjs.org/community/support.html

Community Links

Stack Overflow React tag

Reddit r/reactjs

Reactiflux Discord

React GitHub discussions

Various online blogs and YouTube channels

Community Support

React official documentation

Stack Overflow React tag

Reddit r/reactjs

Reactiflux Discord community

Various online tutorials and YouTube channels

Monetization

Develop React web apps or SaaS products

Create React component libraries

Offer freelance front-end services

Teach React via courses

Contribute to open-source React projects

Future Roadmap

Server Components for SSR and streaming

Concurrent mode and improved rendering

Better integration with React Native

Enhanced developer tooling

Continuous performance optimizations

When Not To Use

For small static websites

Projects not requiring dynamic UI

When SEO is critical without SSR

Low-complexity apps where vanilla JS suffices

Tight resource environments where bundle size matters

Final Summary

React is a component-based library for building dynamic UIs.

It leverages virtual DOM for performance.

Supports declarative and reusable code patterns.

Works for both web (React) and mobile (React Native).

Essential for modern front-end development.

Faq

Is React a framework or library?

React is a library for building UIs, not a full framework.

Does React require a virtual DOM?

Yes, it uses virtual DOM to optimize rendering.

Can I use React with existing projects?

Yes, it can be integrated gradually into existing apps.

What is React Native?

A framework for building mobile apps using React.

Do I need JSX?

JSX is recommended but you can use plain JS with React.createElement.

Code Sample Descriptions

1

React Counter with useState

import React, { useState } from 'react';

const Counter = () => {
    const [count, setCount] = useState(0);
    return (
        <div>
        <h2>Counter: {count}</h2>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
        </div>
    );
};

export default Counter;

Demonstrates a simple counter using React useState hook.

Let’s Try →
2

React Theme Toggle with Context

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

export const useTheme = () => useContext(ThemeContext);

const ThemeProvider = ({ children }) => {
    const [isDark, setIsDark] = useState(false);
    const toggleTheme = () => setIsDark(!isDark);
    return <ThemeContext.Provider value={{ isDark, toggleTheme }}>{children}</ThemeContext.Provider>;
};

export default ThemeProvider;

Uses React Context and useState to toggle dark/light theme.

Let’s Try →
3

React Todo List with useState

import React, { useState } from 'react';

const TodoApp = () => {
    const [todos, setTodos] = useState([]);
    const [task, setTask] = useState('');
    const addTodo = () => setTodos([...todos, { task, completed: false }]);
    const toggleTodo = index => {
        const newTodos = [...todos];
        newTodos[index].completed = !newTodos[index].completed;
        setTodos(newTodos);
    };
    return (
        <div>
        <input value={task} onChange={e => setTask(e.target.value)} />
        <button onClick={addTodo}>Add</button>
        <ul>{todos.map((todo, i) => <li key={i} onClick={() => toggleTodo(i)} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>{todo.task}</li>)}</ul>
        </div>
    );
};

export default TodoApp;

Simple Todo list with add, remove, and toggle completion using useState.

Let’s Try →
4

React Fetch Data with useEffect

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

const DataFetcher = () => {
    const [data, setData] = useState([]);
    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts')
        .then(res => res.json())
        .then(setData);
    }, []);
    return <ul>{data.map(item => <li key={item.id}>{item.title}</li>)}</ul>;
};

export default DataFetcher;

Fetches data from API and displays it using useEffect and useState.

Let’s Try →
5

React Form Handling

import React, { useState } from 'react';

const FormExample = () => {
    const [name, setName] = useState('');
    const handleSubmit = e => { e.preventDefault(); alert(`Hello, ${name}`); };
    return (
        <form onSubmit={handleSubmit}>
        <input value={name} onChange={e => setName(e.target.value)} placeholder="Enter name" />
        <button type="submit">Submit</button>
        </form>
    );
};

export default FormExample;

Demonstrates controlled form inputs and submission handling.

Let’s Try →
6

React Modal Component

import React, { useState } from 'react';

const ModalExample = () => {
    const [isOpen, setIsOpen] = useState(false);
    return (
        <div>
        <button onClick={() => setIsOpen(true)}>Open Modal</button>
        {isOpen && <div className="modal"><p>Modal Content</p><button onClick={() => setIsOpen(false)}>Close</button></div>}
        </div>
    );
};

export default ModalExample;

Displays a modal using conditional rendering and state.

Let’s Try →
7

React useReducer Counter

import React, { useReducer } from 'react';

const reducer = (state, action) => {
    switch(action.type) {
        case 'INCREMENT': return { count: state.count + 1 };
        case 'DECREMENT': return { count: state.count - 1 };
        case 'RESET': return { count: 0 };
        default: return state;
    }
};

const ReducerCounter = () => {
    const [state, dispatch] = useReducer(reducer, { count: 0 });
    return (
        <div>
        <h2>Count: {state.count}</h2>
        <button onClick={() => dispatch({type: 'INCREMENT'})}>+</button>
        <button onClick={() => dispatch({type: 'DECREMENT'})}>-</button>
        <button onClick={() => dispatch({type: 'RESET'})}>Reset</button>
        </div>
    );
};

export default ReducerCounter;

Manages counter state using useReducer hook for more complex logic.

Let’s Try →
8

React Context Counter Example

import React, { createContext, useContext, useState } from 'react';

const CounterContext = createContext();
export const useCounter = () => useContext(CounterContext);

const CounterProvider = ({ children }) => {
    const [count, setCount] = useState(0);
    return <CounterContext.Provider value={{ count, setCount }}>{children}</CounterContext.Provider>;
};

export default CounterProvider;

Shares counter state across components using React Context.

Let’s Try →
9

React Tab Component

import React, { useState } from 'react';

const Tabs = () => {
    const [active, setActive] = useState('tab1');
    return (
        <div>
        <button onClick={() => setActive('tab1')}>Tab 1</button>
        <button onClick={() => setActive('tab2')}>Tab 2</button>
        <div>{active === 'tab1' ? <p>Content 1</p> : <p>Content 2</p>}</div>
        </div>
    );
};

export default Tabs;

Switches between tab content using useState and conditional rendering.

Let’s Try →
10

React LocalStorage Counter

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

const LocalStorageCounter = () => {
    const [count, setCount] = useState(0);
    useEffect(() => {
        const saved = localStorage.getItem('count');
        if (saved) setCount(parseInt(saved, 10));
    }, []);
    useEffect(() => {
        localStorage.setItem('count', count);
    }, [count]);
    return (
        <div>
        <h2>Count: {count}</h2>
        <button onClick={() => setCount(c => c + 1)}>+</button>
        <button onClick={() => setCount(c => c - 1)}>-</button>
        </div>
    );
};

export default LocalStorageCounter;

Persists counter value in localStorage using useEffect.

Let’s Try →

Frequently Asked Questions about React

What is React?

React is a declarative, component-based JavaScript library for building user interfaces, primarily for single-page applications. It allows developers to create reusable UI components and manage application state efficiently.

What are the primary use cases for React?

Single-page web applications (SPAs). Dynamic user interfaces for web apps. Mobile apps via React Native. Reusable component libraries. Interactive dashboards and admin panels

What are the strengths of React?

Reusable and maintainable components. High performance with virtual DOM. Large community and ecosystem. Rich tooling and developer support. Supports both web and mobile (React Native)

What are the limitations of React?

Requires build tools (Webpack, Babel) for JSX. Learning curve for hooks and state management. Not a full framework (needs routing, state libraries). Frequent updates may require learning new APIs. SEO optimization requires server-side rendering or frameworks like Next.js

How can I practice React typing speed?

CodeSpeedTest offers 10+ real React code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpJuliaView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.