React Concepts - Hooks, Props etc.

1/1/1970

React Concepts - Hooks, Props etc.

Resources


Every React Concept Explained in 12 Minutes


Props

Components, Props and JSX in React | Sigma Web Development Course - Tutorial #106

More on Props Understanding Props in ReactJS


Use State Hook

Hooks & State in React | Sigma Web Development Course - Tutorial #107 (Harry)

More on State Hook React useState Hook - React Hooks Explained (Piyush Garg)


Use Effect Hook

The useEffect Hook in React | Sigma Web Development Course - Tutorial #108(Harry)

Basic Syntax :

// App.js
useEffect(()=>){
	// Effect logic here
	return ()=>{ // Return Logic}
},[])

Import:

// App.jsx
import {useEffect} from 'react'

Run on Every Render (i.e. anything render anytime)

useEffect(() => {
  alert("I run on every render!"); // alert everytime something render
});

Run only on first render (i.e. whenever the component itself loaded/reloaded)

useEffect(()=>){
	alert("Hello, This is the first render of App.jsx") // alert everytime component load/reload
},[])

Run whenever a particular state (count) is changed, rendered or reloaded :

const [count, setCount] = useState(0);
 
useEffect(() => {
  alert("Count was changed"); // Alert every time the count changes (even on the first display)
}, [count]);

Run whenever a particular prop (color) is changed, rendered or reloaded :

// Nav.js
import { useEffect } from 'react';
 
const Navbar = ({ color }) => {
  useEffect(() => {
    alert("Color was changed"); // Alert every time the color prop changes (passed via `App.js`)
  }, [color]);
 
  return (
    <div>
      Hello, the color is {color}.
    </div>
  );
};
// App.js
import Navbar from './Nav.js';
 
return (
  ...
  <Navbar color={"navy" + "blue"} />
  ...
);

Run on Every render:

// Nav.js
import { useEffect } from 'react';
 
const Navbar = ({ color }) => {
  useEffect(() => {
    alert("I run on every render"); // Alert every time something renders (e.g., color change and re-render)
  });
  // note: color must be rerender (one way was to make color state and use setColor)
 
  return (
    <div>
      Hello, the color is {color}. 
    </div>
  );
};

Render when the component (Navbar) is mounted and return when it is unmounted:

// Nav.jsx
useEffect(() => {
  alert("Hello, Welcome to my page."); // Runs when the component is rendered (mounted)
 
  return () => {
    alert("Component was unmounted"); // Runs when the component is unmounted
  };
}, []);

Dependency Behavior

Note:

More on Effect Hook React useEffect Hook(Piyush Garg)


Use Context Hook

The useContext hook in React | Sigma Web Development Course - Tutorial #116 (Harry)

React Context provides a way to share data (like state, functions, or themes) across components without passing props through every level of the component tree (avoids prop drilling).

Prop Drilling: passing data from a parent component to a deeply nested child component by passing it as props through intermediate components, even if those intermediate components don't directly use the data.

Let there is a counter count, and we want this count value inside a component Component1.js

App.jsx
	⬊   
	Navbar.jsx
	    ⬊
	    Button.jsx
		    ⬊
			Component1.jsx

We can achieve this by prop drilling, by transferring prop count from app to Navbar then to Button and then finally to Component.

But this is not a good approach, as we are passing a value from one component to others, even it is not required.

// src/App.jsx
const [count, setCount] = useState(0);
const App = () =>{ return( <Navbar count={count}/> }
 
// src/components/Navbar.jsx
const Navbar = ({count}) =>{ return( <Button count={count}/>) }
 
// src/components/Button.jsx
const Button = ({count}) =>{ return( <Component count={count}/>) }
 
// src/components/Component1.jsx
const Component1 = ({count}) =>{ return(<div> {count} </div>) }

*Use case level 1 : Display count in Component1 (Read-Only)

Create Context

// src/context/context.js
 
// import `create` context hook
import {createContext} from "react";
 
// create and export a `context` variable
export const counterContext = createContext(0)

Provide Context in App.jsx

// import the defined counter Context 
import {counterContext} from './context/context'
 
const [count, setCount] = useState(0)
function App(){
	return(
		// wrap the component inside context Provider
		<>
		<counterContext.Provider value={count}>
			<Navbar/>
		</counterContext>
		</>
	)
}

Consume Context in Component1.jsx

// import `use` Context Hook
import {useContext} from 'react'
 
const Component1 = () =>{
	// use the context created inside `context.js` through `useContext`
	const counter = useContext(counterContext)
	return (
		<div>
		{counter} {/*Count Value */}
		</div>
	)
}

Use case level 2 :Update count from Button and Display in Component1

Provide count and setCount in App.jsx

// App.jsx
...
return(
	<counterContext.Provider value={{count, setCount}}>
	</counterContext.Provider>
)
...

Consume count and Display in Component1.jsx

// Component1.jsx
const Component1 = () =>{
	const value = useContext(counterContext)
	return (
		<div>
		{value.counter} {/*count value*/}
		</div>
	)
}

Consume setCount and Update count from Button.jsx

// Button.jsx
 
const Button = () =>{
	const value = useContext(counterContext)
	return(
		<div>
			<button onClick={()=>value.setCount((count)=>count+1)}> {/*setCount function*/}
			</button>	
		</div>
	)
}

Key Note:

Benefit:

Limitations:

Note:

More on Context HOOK React Context API in One Video | ReactJS | ReactJS Tutorial In Hindi(Piyush Garg)


Use Ref Hook

The useRef Hook in React | Sigma Web Development Course - Tutorial #109 (Harry)

Import:

// App.jsx
import {useRef} from 'react'

Example Use Case 1: Persisting Variable Values Across Renders

Consider a counter button:

const [count, setCount] = useState(0);
 
useEffect(() => {
  console.log("re-rendering...");
});

Now, introduce a variable a that increments on every render and logs its value:

let a = 0;
 
useEffect(() => {
  a = a + 1;
  console.log(`re-rendering and value of a is ${a}...`);
});

Issue:

Solution: Using useRef to Persist Values
useRef allows us to persist a value across renders without resetting it:

const a = useRef(0);
 
useEffect(() => {
  a.current = a.current + 1;
  console.log(`re-rendering and value of a is ${a.current}...`);
});

Advantages of useRef:

Comparison of Approaches:

Example Use Case 2: DOM Manipulation with useRef

Scenario:
We have a counter button and need to change its background color without direct DOM manipulation.

<button onClick={() => setCount((count) => count + 1)}>
  count is {count}
</button>

Solution:
Use useRef to reference the DOM element and apply styles in useEffect.

const ref = useRef(); // Create a reference
 
useEffect(() => {
  ref.current.style.backgroundColor = "red"; // Modify the DOM element
}, []); // Only runs on the first render
 
return (
  <button ref={ref} onClick={() => setCount((count) => count + 1)}>
    count is {count}
  </button>
);

Key Points:


More to Learn

1. React Context API

2. React Router

3. State Management Libraries

4. Performance Optimization

5. Advanced React Patterns

6. Backend Integration

7. TypeScript with React