Export and Import in JavaScript (ES6)

1. Default Export

// Exporting (module.js)
export default function greet() {
  console.log("Hello, world!");
}

// Importing (main.js)
import greetFunction from "./module.js";

greetFunction(); // Outputs: Hello, world!

2. Named Export

// Exporting (module.js)
export function greet() {
  console.log("Hello, world!");
}

export const PI = 3.14159;
// Importing (main.js)
import { greet, PI } from "./module.js";

greet(); // Outputs: Hello, world!
console.log(PI); // Outputs: 3.14159

Importing Multiple Named Exports as an Object

// Exporting (module.js)
export function greet() {
  console.log("Hello, world!");
}

export const PI = 3.14159;

export const multiply = (a, b) => a * b;
// Importing as an Object (main.js)
import * as myModule from "./module.js";

myModule.greet(); // Outputs: Hello, world!
console.log(myModule.PI); // Outputs: 3.14159
console.log(myModule.multiply(2, 3)); // Outputs: 6

How It Works:

When to Use

4. Combining Default and Named Exports

// Exporting (module.js)
export default function greet() {
  console.log("Hello, world!");
}

export const PI = 3.14159;
// Importing (main.js)
import greetFunction, { PI } from "./module.js";

greetFunction(); // Outputs: Hello, world!
console.log(PI); // Outputs: 3.14159

Note: greetFunction imports the default export, while { PI } imports the named export.

constant.js

// constant.js
export const API_TIMEOUT = 5000;
export const MAX_USERS = 100;
export const DEFAULT_LANGUAGE = "en";

What is Hook in React?

Why use Hooks?

Common React Hooks

What is One-Way Data Binding?

Why Do We Need State Variables in React?

useState Hook

  1. State Variable: The current value of the state.
  2. Setter Function: A function to update the state value.

Syntax

const [state, setState] = useState(initialValue);

Elements Returned

  1. State Variable(state):
  1. Setter Function (setState):

Example

import React, { useState } from "react";

function Counter() {
  // Declare a state variable "count" with initial value 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default Counter;