Fixing TS7016 Error in React: Could Not Find a Declaration File for Module react-router-dom

While working with a React + TypeScript project, you may suddenly see this error:

TS7016: Could not find a declaration file for module 'react-router-dom'

or:

implicitly has an 'any' type

This is a very common error when using TypeScript in React applications.

In this article, we’ll clearly understand:

  • What this error means
  • Why it happens
  • How to fix it
  • What are declaration files
  • Why TypeScript needs them
  • Best practices

The Exact Error

Your error looks like this:

TS7016: Could not find a declaration file for module 'react-router-dom'.'/node_modules/react-router-dom/index.js'implicitly has an 'any' type.

And this line causes the error:

import { NavLink } from 'react-router-dom';

What Does This Error Mean?

TypeScript is saying:

“I found the react-router-dom package, but I cannot find its type definitions.”

In simple words:

👉 TypeScript understands JavaScript code
❌ But it does NOT know the types of the package.


Why TypeScript Needs Types

TypeScript works using:

  • types
  • interfaces
  • definitions

Example:

let name: string = "Raju";

TypeScript knows:

  • name must be string

Similarly, TypeScript wants type information for external libraries too.


What Are Declaration Files?

Declaration files are:

.d.ts

files.

These files tell TypeScript:

  • what functions exist
  • what props exist
  • what return types exist

Example

Without types:

function add(a, b) {
return a + b;
}

TypeScript does not know:

  • what a is
  • what b is

With Types

function add(a: number, b: number): number {
return a + b;
}

Now TypeScript understands everything clearly.


Why This Error Happens

Usually because:

  • @types/react-router-dom package is missing
  • TypeScript cannot find declaration files
  • Package version mismatch
  • Incomplete installation

Most Common Fix

Install Type Definitions.

Run:

npm install --save-dev @types/react-router-dom

or

yarn add -D @types/react-router-dom

What This Package Does

This package provides:

type definitions

for:

react-router-dom

Now TypeScript can understand:

  • NavLink
  • Route
  • BrowserRouter
  • useNavigate
  • etc.

After Installation

Restart your React server:

npm start

or

npm run dev

Important Version Issue

This is VERY important.


⚠️ React Router v6+

If you are using:

react-router-dom v6 or later

then many times:

👉 type definitions are already included.

You may NOT need:

@types/react-router-dom

Then Why Error Happens?

Usually because:

  • corrupted node_modules
  • old TypeScript version
  • package mismatch
  • partial installation

Recommended Fix for React Router v6+

Delete:

node_modulespackage-lock.json

Then reinstall:

npm install

Check Installed Version

Run:

npm list react-router-dom

If Using React Router v5

Then install:

npm install --save-dev @types/react-router-dom

because v5 needs separate type definitions.


How TypeScript Reads Packages

When you import:

import { NavLink } from 'react-router-dom';

TypeScript searches for:

1. package2. type definitions3. .d.ts files

If type definitions are missing:

❌ TS7016 error occurs.


Temporary Quick Fix (Not Recommended)

You may see suggestions like:

declare module 'react-router-dom';

inside a .d.ts file.

This removes the error temporarily.

BUT:

❌ You lose type safety.


Why You Should Avoid This

Because TypeScript will treat everything as:

any

which defeats the purpose of TypeScript.


Best Solution

Always use proper type definitions.


❌ Before Fix

import { NavLink } from 'react-router-dom';

Error:

Could not find declaration file

✅ After Fix

npm install --save-dev @types/react-router-dom

Now error disappears.


Another Possible Issue

Sometimes developers accidentally install:

react-router

instead of:

react-router-dom

Make sure correct package exists.


Verify in package.json

"react-router-dom": "^6.x.x"

Recommended TypeScript Setup

Install:

npm install typescript @types/react @types/react-dom

Important Learning

JavaScript libraries work WITHOUT types.

But TypeScript applications need:

  • declarations
  • interfaces
  • type definitions

to provide:

  • autocomplete
  • validation
  • error checking
  • IntelliSense

Final Summary

✔ TS7016 means TypeScript cannot find type definitions
✔ Usually happens with missing @types/... packages
✔ Install correct type definitions
✔ Restart development server after installation
✔ React Router v6+ usually includes types already
✔ Version mismatch can also cause this error


Quick Fix Checklist

Before debugging deeply, check:

react-router-dom installed
✅ correct version installed
@types/react-router-dom installed (for v5)
✅ restart server
✅ delete node_modules and reinstall if needed


🚀 Call to Action

💡 Found this helpful? Subscribe for simple React and TypeScript debugging guides with real-world examples. Happy Coding!

Can We Use Both .js and .tsx Files in a React Project? (Complete Guide)

Many developers moving from JavaScript to TypeScript have this question:

🤔 “Can I use both .js and .tsx files in the same React project?”

The answer is:

✅ YES — absolutely.

In fact, many real-world React applications use a mix of:

  • .js
  • .jsx
  • .ts
  • .tsx

especially during migration from JavaScript to TypeScript.

In this guide, you’ll learn:

  • What .js and .tsx files are
  • Can they work together
  • Real-world usage
  • Benefits and drawbacks
  • Best practices

📌 Understanding File Types

Before understanding mixed usage, let’s quickly understand each file type.


🔹 What is .js?

.js means:

JavaScript file

Example:

function add(a, b) {
return a + b;
}

🔹 What is .tsx?

.tsx means:

TypeScript + JSX file

Used when:

  • Writing React components
  • Using TypeScript types

Example:

type Props = {
name: string;
};
function User({ name }: Props) {
return <h1>{name}</h1>;
}

Can They Work Together?

YES ✅

You can absolutely use:

  • .js
  • .jsx
  • .ts
  • .tsx

inside the same React project.


Real-World Scenario

Many companies:

  • Start project in JavaScript
  • Slowly migrate to TypeScript

So they temporarily have:

src/ ├── App.tsx ├── Header.jsx ├── utils.js ├── api.ts └── Dashboard.tsx

👉 This is completely normal.


How Does It Work?

When using TypeScript in React:

👉 TypeScript compiler can understand JavaScript files too.


Important Configuration

In tsconfig.json:

{
"compilerOptions": { "allowJs": true }
}

What Does allowJs Do?

"allowJs": true

👉 Allows TypeScript to compile .js files also.

Without this:

❌ TypeScript may ignore JS files.


Example Project Structure

Example

src/ ├── components/ │ ├── Button.tsx │ ├── Navbar.jsx │ ├── utils/ │ ├── math.js │ ├── api.ts │ └── App.tsx

👉 All these files can work together.


Importing Between JS and TSX


✅ Import JS into TSX

import add from "./utils/math";

✅ Import TSX Component

import Button from "./components/Button";

Why Developers Mix .js and .tsx


✅ 1. Gradual Migration

Big applications cannot migrate instantly.

So teams:

  • Convert slowly
  • File by file

✅ 2. Legacy Code Support

Old JavaScript files may still work perfectly.


✅ 3. Faster Development

Some utility files may remain simple .js.


Important Differences

Feature.js.tsx
Type Safety❌ No✅ Yes
IntelliSenseLimitedBetter
Compile Checks
React JSX Support

Benefits of Using .tsx

✅ Better Error Detection

TypeScript catches mistakes early.


✅ Strong Type Safety

type User = { name: string; };

✅ Better Developer Experience

  • Auto suggestions
  • Safer refactoring
  • Better maintainability

Problems You May Face

❌ 1. Type Errors with JS Files

Sometimes TypeScript cannot understand JS structure properly.


❌ 2. Inconsistent Codebase

Mixing too many styles may confuse developers.


❌ 3. Any-Type Problems

JS files may reduce type safety.


Best Practice (Recommended)

✅ Recommended Approach

If possible:

👉 Gradually move toward TypeScript


🚀 Good Strategy

Step 1

Keep old files in JS.


Step 2

Write new components in TSX.


Step 3

Slowly migrate old files.


Example Migration

Old JS Component

function Button(props) {
return <button>{props.title}</button>;
}

Migrated TSX Component

type Props = { title: string;};
function Button({ title }: Props) {
return <button>{title}</button>;
}

Important Note About .ts vs .tsx

ExtensionPurpose
.tsTypeScript without JSX
.tsxTypeScript with JSX

Interview Question

❓ Can we use .js and .tsx together in React?

👉 Answer:

Yes. React projects can use both JavaScript and TypeScript files together. TypeScript supports gradual migration using allowJs.


Final Summary

.js and .tsx can work together
✔ Common in real-world migration projects
✔ Use allowJs: true in TypeScript config
✔ TSX provides better type safety
✔ Gradual migration is best practice


💡 Found this helpful? Subscribe for simple React and TypeScript guides with real-world examples. Happy Coding!

React.memo and Composition in React (Complete Guide with Detailed Examples)

When building React applications, two concepts help developers create:

✅ Faster applications
✅ Cleaner code
✅ Reusable components
✅ Better maintainability

Those concepts are:

  • React.memo
  • Component Composition

In this guide, you’ll learn both concepts clearly with real-world examples.


What You Will Learn

✔ What is React.memo
✔ Why we need it
✔ How it improves performance
✔ What is Composition
✔ Why Composition is preferred in React
✔ Real-world examples for both


Part 1: Understanding React.memo

What is React.memo?

Simple Definition

React.memo is a higher-order component that prevents unnecessary re-rendering of functional components.


Why Do We Need React.memo?

In React:

👉 Parent component re-renders
➡ Child components also re-render

Even if:

  • Props did not change
  • UI did not change

This can reduce performance.


Example Without React.memo

❌ Code

import { useState } from "react";

function Child() {
console.log("Child Rendered");
return <h2>Child Component</h2>;
}

function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<Child />
</div>
);
}

export default App;

What Happens Here?

Whenever count changes:

setCount(count + 1)

👉 Parent re-renders
👉 Child ALSO re-renders

Even though Child has no relation to count.


Optimized with React.memo

✅ Code

import { memo } from "react";

const Child = memo(function Child() {
console.log("Child Rendered");
return <h2>Child Component</h2>;
});

export default Child;

Now What Happens?

When parent re-renders:

👉 React compares previous props vs new props

If props are same:

✅ Child render is skipped


Important Rule

React.memo works best when:

✔ Props are stable
✔ Component renders frequently
✔ Rendering is expensive


⚠️ Example Where React.memo Fails

❌ Problem

<Child data={{ name: "React" }} />

Why?

Because:

{ name: "React" }

creates a NEW object every render.

👉 React thinks props changed.


Fix with useMemo

const data = useMemo(() => ({
name: "React"
}), []);

Real-World Example

Imagine:

  • Dashboard with charts
  • Huge tables
  • Complex UI

Without optimization:

❌ Unnecessary renders
❌ Slow UI

With React.memo:

✅ Better performance


When NOT to Use React.memo

Avoid if:

  • Component is very small
  • Props change frequently
  • Optimization not needed

👉 Overusing memo can increase complexity.


Interview Tip

❓ What is React.memo?

👉 Answer:

React.memo prevents unnecessary re-rendering of functional components by memoizing rendered output based on props comparison.


Part 2: Understanding Composition in React

📌 What is Composition?

Simple Definition

Composition means building complex UI using smaller reusable components.


Basic Composition Example

🔹 Button Component

function Button({ children }) {
return (
<button>
{children}
</button>
);
}

🔹 Usage

<Button>Save</Button>
<Button>Delete</Button>

Why Composition is Powerful

Composition helps:

✅ Reusability
✅ Cleaner architecture
✅ Scalability
✅ Separation of concerns


Composition with Layouts

Card Component

function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}

Usage

<Card>
<h2>React</h2>
<p>Composition Example</p>
</Card>

Composition Using Props

Modal Component

function Modal({ title, content, footer }) {
return (
<div className="modal">
<h2>{title}</h2>
<div>{content}</div>
<footer>{footer}</footer>
</div>
);
}

Usage

<Modal
title="Delete User"
content={<p>Are you sure?</p>}
footer={<button>Confirm</button>}
/>

Composition vs Inheritance

React documentation recommends:

✅ Composition
❌ Inheritance


Inheritance Problem

Inheritance creates:

  • Tight coupling
  • Complexity

Composition Advantage

Composition provides:

  • Flexibility
  • Better maintainability

Advanced Composition Pattern

Compound Components

Example:

<Tabs>
<Tabs.List />
<Tabs.Panel />
</Tabs>

Used in:

  • UI libraries
  • Design systems

Combining React.memo + Composition

This is common in real applications.

Example

const Card = memo(function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
});

👉 Reusable + optimized


Common Mistakes

❌ Overusing React.memo

Not every component needs memoization.


❌ Creating Huge Components

Break UI into reusable pieces.


❌ Deep Prop Drilling

Use:

  • Context API
  • Composition patterns

Best Practices

✅ Use React.memo Carefully

Optimize only where needed.


✅ Prefer Composition

Build UI using reusable blocks.


✅ Keep Components Small

Small components:

  • Easier to test
  • Easier to reuse

Final Summary

React.memo

✔ Prevents unnecessary re-renders
✔ Improves performance
✔ Best for stable props


Composition

✔ Builds reusable UI
✔ Cleaner architecture
✔ Recommended React pattern


💡 Found this helpful? Subscribe for simple React guides, real-world examples, and interview preparation tips. Happy Coding!

Manipulating the DOM with useRef in React (Complete Guide with Examples)

When learning React, most developers use state and props to update the UI.

But sometimes, we need to directly access or manipulate a DOM element like:

  • Focusing an input
  • Playing a video
  • Scrolling to a section
  • Accessing element size

That’s where the useRef hook becomes very useful.

In this guide, you’ll learn:

  • What useRef is
  • Why we need it
  • How it manipulates the DOM
  • Best real-world examples
  • Common mistakes

What is useRef?

Simple Definition

useRef is a React hook that allows us to persist values and directly access DOM elements without re-rendering the component.


Syntax

const refName = useRef(initialValue);

How useRef Works

const inputRef = useRef(null);

React creates an object like:

{
current: null
}

When attached to an element:

<input ref={inputRef} />

inputRef.current now points to the actual DOM element.


Why Do We Need useRef?

Normally in React:

✅ UI updates through state

But sometimes we need:

  • Direct DOM access
  • Performance optimization
  • Persistent values without re-render

👉 useRef solves this.


Example 1: Focus Input Automatically

One of the most common use cases.

Code

import { useRef } from "react";

function App() {

const inputRef = useRef(null);

const focusInput = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>
Focus Input
</button>
</div>
);
}

export default App;

How It Works ?

Step 1

const inputRef = useRef(null);

Creates reference object.


Step 2

<input ref={inputRef} />

Connects DOM element to ref.


Step 3

inputRef.current.focus();

Directly accesses DOM element and focuses input.


Example 2: Change Background Color

Code

import { useRef } from "react";

function App() {

const boxRef = useRef(null);

const changeColor = () => {
boxRef.current.style.backgroundColor = "blue";
};

return (
<div>
<div
ref={boxRef}
style={{
width: "200px",
height: "200px",
background: "gray"
}}
/>
<button onClick={changeColor}>
Change Color
</button>
</div>
);
}

Example 3: Auto Scroll to Section

Very useful in landing pages.

Code

import { useRef } from "react";

function App() {

const sectionRef = useRef(null);

const scrollToSection = () => {
sectionRef.current.scrollIntoView({
behavior: "smooth"
});
};

return (
<div>
<button onClick={scrollToSection}>
Go to Section
</button>
<div style={{ height: "100vh" }} />
<div ref={sectionRef}>
Target Section
</div>
</div>
);
}

Example 4: Video Play/Pause Control

Code

import { useRef } from "react";

function App() {

const videoRef = useRef(null);

return (
<div>
<video
ref={videoRef}
width="400"
src="video.mp4"
/>
<button onClick={() => videoRef.current.play()}>
Play
</button>
<button onClick={() => videoRef.current.pause()}>
Pause
</button>
</div>
);
}

Example 5: Store Previous Value Without Re-render

Code

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

function App() {
const [count, setCount] = useState(0);
const previousCount = useRef(0);

useEffect(() => {
previousCount.current = count;
}, [count]);

return (
<div>
<h2>Current: {count}</h2>
<h2>Previous: {previousCount.current}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}

Important Difference: useRef vs useState

FeatureuseRefuseState
Causes re-render❌ No✅ Yes
Stores value✅ Yes✅ Yes
Access DOM✅ Yes❌ No

Best Use Cases of useRef

Use useRef for:

✅ DOM access
✅ Focus management
✅ Scroll handling
✅ Timers
✅ Storing mutable values


Common Mistakes

❌ Manipulating DOM Too Much

React prefers declarative UI.

👉 Don’t overuse direct DOM manipulation.


❌ Accessing .current Before Render

console.log(ref.current);

May be null initially.


❌ Using useRef Instead of State

If UI must update → use state.


Interview Question

❓ What is useRef in React?

👉 Answer:

useRef is a hook used to persist values across renders and directly access DOM elements without causing re-renders.


Final Summary

  • useRef gives direct DOM access
  • Does not trigger re-render
  • Useful for focus, scroll, video control, timers
  • Should be used carefully

💡 Found this helpful? Subscribe for simple React guides, real-world examples, and interview preparation tips. Happy Coding!

React SVG Import: What Does “ReactComponent as” Mean?

If you’ve worked with React, you might have seen this syntax:

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

And wondered:

🤔 What is ReactComponent?
🤔 How is an SVG becoming a React component?
🤔 When should we use this?

Let’s break it down step-by-step in a very simple way 👇


What Does This Syntax Mean?

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

👉 This means:

“Import the SVG file and use it as a React component”


Usage

<SomeIcon />

👉 Instead of:

<img src="some-icon.svg" />

How Does This Actually Work?

This is not plain JavaScript behavior.

👉 It is handled by your build tool (like Webpack or Vite).


Behind the Scenes

Tools like:

  • SVGR (SVG to React transformer)

convert your SVG file into:

function SomeIcon(props) {
return (
<svg {...props}>
{/* SVG content */}
</svg>
);
}

👉 So your SVG becomes a React component internally


Normal SVG vs React Component

❌ Traditional Way

<img src="/icon.svg" alt="icon" />

✅ React Component Way

import { ReactComponent as Icon } from './icon.svg';

<Icon />

Why Use SVG as React Component?


1. Easy Styling

<Icon style={{ color: 'red', width: 50 }} />

👉 You can style it like a component


2. Dynamic Props

<Icon width={30} height={30} />

3. Better Control

You can:

  • Change color
  • Animate
  • Add events

Add Event Handlers

<Icon onClick={() => alert('Clicked')} />

Example (Real Usage)

SVG File

<!-- icon.svg -->
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>

React Usage

import { ReactComponent as Icon } from './icon.svg';

function App() {
return <Icon width={40} height={40} />;
}

Styling with CSS

.icon {
fill: blue;
}
<Icon className="icon" />

Important Note (Color Control)

For dynamic color:

👉 SVG must use:

fill="currentColor"

👉 Then:

<Icon style={{ color: 'green' }} />

Common Mistakes

❌ Using wrong import

import Icon from './icon.svg'; // ❌

👉 This gives image path, not component


❌ Missing configuration

👉 Works only if:

  • CRA (Create React App)
  • Vite (with plugin)
  • Webpack configured

When It Works Automatically

Works out-of-the-box in:

  • Create React App
  • Vite (with SVGR plugin)
  • Next.js (with config)

When to Use <img> vs Component

Use <img> when:

  • Simple display
  • No styling needed

Use React Component when:

  • Need styling
  • Need animations
  • Need dynamic behavior

Interview Tip

If asked:

“What is ReactComponent as in SVG import?”

👉 Answer:

“It converts SVG into a React component using tools like SVGR, allowing us to use it like JSX.”


Final Summary

  • ReactComponent converts SVG → React component
  • Enables styling, events, and dynamic behavior
  • Powered by tools like SVGR
  • Better than <img> for interactive UI

Related Articles


💡 Found this helpful? Subscribe for simple React tips, real-world examples, and developer-friendly tutorials. Happy Coding!