\n \n \n \n","@type":"SoftwareSourceCode","programmingLanguage":"html"},{"@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-6","text":"// Minimal React app structure (modern bundler)\nimport React, { useState } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nfunction App() {\n const [text, setText] = useState('Hello React');\n return (\n
\n

{text}

\n \n
\n );\n}\n\ncreateRoot(document.getElementById('root')).render();","programmingLanguage":"jsx","@type":"SoftwareSourceCode"},{"programmingLanguage":"javascript","@type":"SoftwareSourceCode","text":"import React, { useState } from 'react';\n\nfunction Counter() {\n const [count, setCount] = useState(0);\n return (\n
\n

Count: {count}

\n \n
\n );\n}\n\nfunction Greeting({ name }) {\n return

Hello, {name}!

;\n}\n\nexport default function App() {\n return (\n
\n \n \n
\n );\n}","@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-7"},{"@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-8","@type":"SoftwareSourceCode","programmingLanguage":"javascript","text":"import React, { useEffect, useState } from 'react';\n\nfunction Posts() {\n const [posts, setPosts] = useState([]);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n\n useEffect(() => {\n fetch('/api/posts')\n .then((r) => {\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r.json();\n })\n .then((data) => {\n setPosts(data);\n setLoading(false);\n })\n .catch((err) => {\n setError(err.message);\n setLoading(false);\n });\n }, []);\n\n if (loading) return
Loading…
;\n if (error) return
Error: {error}
;\n\n return (\n
    \n {posts.map((p) => (\n
  • {p.title}
  • \n ))}\n
\n );\n}"},{"@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-9","programmingLanguage":"javascript","@type":"SoftwareSourceCode","text":"// A small standalone async function illustrating error handling and retries\nasync function fetchWithRetry(url, retries = 2) {\n for (let i = 0; i <= retries; i++) {\n try {\n const res = await fetch(url);\n if (!res.ok) throw new Error(`Status ${res.status}`);\n return await res.json();\n } catch (e) {\n if (i === retries) throw e;\n await new Promise((r) => setTimeout(r, 500));\n }\n }\n}"},{"@type":"SoftwareSourceCode","@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-10","programmingLanguage":"javascript","text":"import React, { memo, useMemo } from 'react';\n\nfunction ExpensiveList({ items }) {\n // Simulate a heavy computation\n const computed = useMemo(() => items.map((i) => i * 2), [items]);\n return (\n
    \n {computed.map((n, idx) => (\n
  • {n}
  • \n ))}\n
\n );\n}\n\nconst App = memo(function App({ data }) {\n return (\n
\n

Performance Patterns

\n \n
\n );\n});"},{"programmingLanguage":"javascript","@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-11","text":"// Lazy loading a component\nimport React, { Suspense, lazy } from 'react';\nconst Dashboard = lazy(() => import('./Dashboard'));\n\nexport default function AppWrapper() {\n return (\n Loading dashboard…
}>\n \n \n );\n}","@type":"SoftwareSourceCode"},{"@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-12","@type":"SoftwareSourceCode","programmingLanguage":"javascript","text":"// Simple error boundary\nimport React from 'react';\n\nclass ErrorBoundary extends React.Component {\n constructor(props) { super(props); this.state = { hasError: false }; }\n static getDerivedStateFromError() { return { hasError: true }; }\n render() {\n if (this.state.hasError) return
Something went wrong.
;\n return this.props.children;\n }\n}\n\nexport default ErrorBoundary;"},{"@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#code-13","text":"// Very small unit test example (conceptual)\nimport { sum } from './utils';\n\ntest('sum adds numbers correctly', () => {\n expect(sum(1, 2)).toBe(3);\n});","programmingLanguage":"javascript","@type":"SoftwareSourceCode"}]},{"@type":"BreadcrumbList","itemListElement":[{"position":1,"item":"https://javacripting.com","@type":"ListItem","name":"Home"},{"position":2,"name":"JavaScript Projects","@type":"ListItem","item":"https://javacripting.com/javascript-projects"},{"name":"javascript and react js: A Practical Guide for Modern Frontend Development","@type":"ListItem","item":"https://javacripting.com/javascript-projects/javascript-and-react-js","position":3}],"@id":"https://javacripting.com/javascript-projects/javascript-and-react-js#breadcrumb"},{"@type":"FAQPage","mainEntity":[{"name":"What is the relationship between JavaScript and React?","acceptedAnswer":{"text":"JavaScript provides the language runtime React uses; React is a library built in JavaScript for building UI components. React adds a declarative way to describe UI and updates efficiently.","@type":"Answer"},"@type":"Question"},{"name":"Do I need deep JavaScript knowledge to start with React?","acceptedAnswer":{"text":"A solid grasp of JavaScript fundamentals helps, especially functions, objects, arrays, and ES6 syntax. You can start with basic React concepts while improving JS skills in parallel.","@type":"Answer"},"@type":"Question"},{"acceptedAnswer":{"text":"Yes. You can prototype with a CDN-based setup using script tags, then migrate to a bundler when the project grows.","@type":"Answer"},"@type":"Question","name":"Can I use React without build tools?"},{"name":"Is React still relevant in 2026?","acceptedAnswer":{"text":"React remains a dominant UI library due to its ecosystem, performance patterns, and broad community support, though other stacks may suit some projects.","@type":"Answer"},"@type":"Question"},{"name":"How do I debug React components effectively?","@type":"Question","acceptedAnswer":{"@type":"Answer","text":"Use React DevTools to inspect components, props, and hooks, and supplement with console logging and browser dev tools for network and performance analysis."}}]}]}

JavaScript and React JS: A Practical Guide

A comprehensive, developer-focused guide to using JavaScript with React JS. Learn setup, components, state, data fetching, performance optimization, debugging, and best practices with concrete code examples and actionable steps.

JavaScripting
JavaScripting Team
·5 min read
JavaScript and React Guide - JavaScripting
Quick AnswerDefinition

JavaScript is the language that powers the web, and React JS is a library that makes building user interfaces with JavaScript fast, predictable, and scalable. This article explains how the two work together, how to set up a modern development environment, and practical patterns for components, state, data fetching, and performance optimization.

What are JavaScript and React JS? How they relate

JavaScript is the core programming language of the web, responsible for adding interactivity, data processing, and logic to web pages. React JS, a JavaScript library, provides a declarative way to build UIs using components, a virtual DOM, and predictable rendering. Together, they enable scalable frontends where UI is composed of independent, reusable pieces. This section shows a vanilla JavaScript snippet and a simple React component to illustrate the contrast and synergy.

JavaScript
// Vanilla JS helper function function greet(name) { return `Hello, ${name}!`; } console.log(greet('World'));
JSX
// Simple React component (JSX) import React from 'react'; function Greeting({ name }) { return <div>Hello, {name}! 👋</div>; } export default Greeting;
  • In plain JS, you manipulate the DOM directly.
  • In React, you describe what UI should look like and let the library reconcile changes efficiently.
  • The power of combining them comes from using React to render UIs while writing business logic and data handling in JavaScript.

Why this matters: This combination lets you scale from tiny widgets to full-fledged SPAs with maintainable code and a robust ecosystem.

Setting up a modern development environment

A practical setup uses Node.js, npm or yarn, and a modern bundler like Vite or Create React App. The minimal steps below outline starting a project with Vite and React. You’ll see a package.json scaffold, dev script, and a quick run command.

Bash
# Create a new React project with Vite npm create vite@latest my-app -- --template react cd my-app npm install
JSON
// package.json (excerpt) { "name": "my-app", "scripts": { "start": "vite", "build": "vite build", "preview": "vite preview" }, "dependencies": { "react": "^18.0.0", "react-dom": "^18.0.0" }, "devDependencies": { "vite": "^4.0.0" } }

Configuration tips:

  • Use ES modules import paths for React components.
  • Enable fast refresh via your bundler for a smooth dev experience.
  • Keep dependencies up to date with semantic versioning in mind.

Enhanced workflow:

  • Integrate a linter (ESLint) and formatter (Prettier) to maintain code quality.
  • Add a lightweight testing setup (e.g., Vitest) for unit tests.

Why this matters: A modern toolchain speeds up iteration, ensures consistency, and reduces configuration drift as your app grows.

Building a simple React app that interacts with vanilla JS

A practical approach is to prototype a React UI with a CDN-based setup first, then migrate to a bundler as needs grow. This demonstrates how React and plain JavaScript can co-exist in a single page to showcase events, DOM updates, and component rendering.

HTML
<!doctype html> <html> <head> <meta charset="UTF-8" /> <title>React with CDN</title> </head> <body> <div id="root"></div> <script src="https://unpkg.com/react@18/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <script> const App = () => { const [count, setCount] = React.useState(0); return React.createElement('div', null, React.createElement('button', { onClick: () => setCount(count + 1) }, 'Increment'), React.createElement('span', null, ' Count: ' + count) ); }; ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(App)); </script> </body> </html>
JSX
// Minimal React app structure (modern bundler) import React, { useState } from 'react'; import { createRoot } from 'react-dom/client'; function App() { const [text, setText] = useState('Hello React'); return ( <div> <h1>{text}</h1> <button onClick={() => setText('You clicked!')}>Click me</button> </div> ); } createRoot(document.getElementById('root')).render(<App />);

What you gain from this approach:

  • Clarity on how React renders components and updates the DOM.
  • A safer path to migrate toward a build system with JSX support.
  • A quick feedback loop when you’re learning core concepts like props and state.

Why this matters: Understanding the transition from CDN-based prototypes to a real project scaffolding helps you plan architecture and tooling early.

State management and props in React

React state lets components manage data that changes over time, while props enable data to flow from parent to child components. In this section, you’ll see a simple counter using useState and a child component that receives data via props.

JavaScript
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } function Greeting({ name }) { return <h2>Hello, {name}!</h2>; } export default function App() { return ( <div> <Greeting name="Alex" /> <Counter /> </div> ); }

Key takeaways:

  • State is local to a component unless lifted up.
  • Props provide a controlled data flow from parent to child.
  • Keeping components small makes state management easier.

Why this matters: Props and state underpin dynamic UIs and composeability in React, enabling predictable data flow and reusability.

Integrating JavaScript with React: fetch API and async patterns

Fetch patterns in React typically involve useEffect for side effects like data loading, plus useState to store results and loading/error states. This example demonstrates a component that fetches posts and renders them, with basic error handling.

JavaScript
import React, { useEffect, useState } from 'react'; function Posts() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('/api/posts') .then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }) .then((data) => { setPosts(data); setLoading(false); }) .catch((err) => { setError(err.message); setLoading(false); }); }, []); if (loading) return <div>Loading…</div>; if (error) return <div>Error: {error}</div>; return ( <ul> {posts.map((p) => ( <li key={p.id}>{p.title}</li> ))} </ul> ); }
JavaScript
// A small standalone async function illustrating error handling and retries async function fetchWithRetry(url, retries = 2) { for (let i = 0; i <= retries; i++) { try { const res = await fetch(url); if (!res.ok) throw new Error(`Status ${res.status}`); return await res.json(); } catch (e) { if (i === retries) throw e; await new Promise((r) => setTimeout(r, 500)); } } }

Why it matters: React code often needs asynchronous data and robust error handling. Structuring state for loading and errors improves UX and reliability, while patterns like retries help resilience in unreliable networks.

Performance tips and best practices

Performance matters in React apps. This section covers memoization, lazy loading, and efficient re-renders to keep apps responsive as they scale. Keeping components pure where possible makes it easier for React to reuse previous renders.

JavaScript
import React, { memo, useMemo } from 'react'; function ExpensiveList({ items }) { // Simulate a heavy computation const computed = useMemo(() => items.map((i) => i * 2), [items]); return ( <ul> {computed.map((n, idx) => ( <li key={idx}>{n}</li> ))} </ul> ); } const App = memo(function App({ data }) { return ( <div> <h1>Performance Patterns</h1> <ExpensiveList items={data} /> </div> ); });
JavaScript
// Lazy loading a component import React, { Suspense, lazy } from 'react'; const Dashboard = lazy(() => import('./Dashboard')); export default function AppWrapper() { return ( <Suspense fallback={<div>Loading dashboard…</div>}> <Dashboard /> </Suspense> ); }

Tips:

  • Prefer memoization for heavy computations and components that render often with unchanged props.
  • Use keys for list rendering to help React track changes efficiently.
  • Break large UI into smaller chunks and load them lazily when needed.

Why this matters: Performance patterns help you maintain snappy UIs as your React app grows, while keeping code readable and maintainable.

Debugging and testing strategies

Debugging React apps involves using browser dev tools, React DevTools, and careful logging. A simple error boundary helps catch runtime errors without crashing the entire app, and tests provide confidence during refactors.

JavaScript
// Simple error boundary import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } render() { if (this.state.hasError) return <div>Something went wrong.</div>; return this.props.children; } } export default ErrorBoundary;
JavaScript
// Very small unit test example (conceptual) import { sum } from './utils'; test('sum adds numbers correctly', () => { expect(sum(1, 2)).toBe(3); });

Additional notes:

  • Use console.log judiciously; remove noisy logs before production.
  • Keep a habit of running tests before merging changes.
  • Leverage React DevTools to inspect props, state, and component trees.

Why this matters: Debugging and testing practices reduce bugs and make large React app maintenance feasible, especially when working with complex state and asynchronous data flows.

Steps

Estimated time: 60-90 minutes

  1. 1

    Install and initialize tooling

    Install Node.js and create a new React project scaffold (Vite). Initialize the repository and install dependencies to start coding.

    Tip: Use the official templates to avoid misconfigurations.
  2. 2

    Add React dependencies

    Install react and react-dom and verify the package.json scripts for dev/build, ensuring the environment supports JSX.

    Tip: Prefer local projects over global installs.
  3. 3

    Create a minimal component structure

    Build a simple App component and a child to demonstrate props and composition.

    Tip: Keep components small and focused.
  4. 4

    Run the development server

    Start the dev server, open the browser, and verify hot reload works as you edit.

    Tip: Check console for runtime warnings early.
  5. 5

    Add data fetching and state

    Introduce useState and useEffect to fetch data and manage loading and errors.

    Tip: Gracefully handle loading and error states.
  6. 6

    Optimize and test

    Apply memoization and code-splitting; run tests and linting before merging.

    Tip: Automate tests to catch regressions.
Pro Tip: Leverage JSX to keep UI code declarative and readable.
Warning: Avoid mutating state directly; use setter functions.
Note: Use React DevTools to inspect component trees and props.
Note: Prefer code-splitting and lazy loading for large apps.

Prerequisites

Required

  • Required
  • npm or yarn
    Required
  • Basic JavaScript knowledge
    Required
  • A modern browser (Chrome/Edge) for testing
    Required

Keyboard Shortcuts

ActionShortcut
Open Command PaletteVS Code or similar editorCtrl++P
Format DocumentAuto-format code+Alt+F
Toggle Integrated TerminalQuick access to terminalCtrl+`
Find in FilesGlobal searchCtrl++F
Toggle Line CommentComment blocks quicklyCtrl+/

Questions & Answers

What is the relationship between JavaScript and React?

JavaScript provides the language runtime React uses; React is a library built in JavaScript for building UI components. React adds a declarative way to describe UI and updates efficiently.

JavaScript provides the language; React is a UI library built with JavaScript that helps you build components and manage updates efficiently.

Do I need deep JavaScript knowledge to start with React?

A solid grasp of JavaScript fundamentals helps, especially functions, objects, arrays, and ES6 syntax. You can start with basic React concepts while improving JS skills in parallel.

Yes, understanding JavaScript basics makes learning React much smoother.

Can I use React without build tools?

Yes. You can prototype with a CDN-based setup using script tags, then migrate to a bundler when the project grows.

You can prototype with React via CDNs, and upgrade to a bundler later.

Is React still relevant in 2026?

React remains a dominant UI library due to its ecosystem, performance patterns, and broad community support, though other stacks may suit some projects.

React is still widely used and actively developed in 2026.

How do I debug React components effectively?

Use React DevTools to inspect components, props, and hooks, and supplement with console logging and browser dev tools for network and performance analysis.

Use React DevTools and console logs to debug components efficiently.

What to Remember

  • Understand how JavaScript and React JS complement each other to build UIs.
  • Set up a modern environment with React tooling for productive development.
  • Use components and state to create dynamic, maintainable interfaces.
  • Fetch data with proper async patterns and handle errors gracefully.

Related Articles