React Hooks

React Hooks

React Hooks were introduced in React 16.8 to allow functional components to manage state and side effects without needing class components. Hooks simplify state management and component lifecycle methods.

useState Hook

The useState hook is used to manage state in a function component.

👉 Example: Counter using useState

import React, { useState } from ‘react’;

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count – 1)}>Decrease</button>
</div>
);
}

export default Counter;

📝 How it Works:

✔ useState(0) initializes state with 0.
✔ count holds the current state value.
✔ setCount updates the state and triggers a re-render.

useEffect Hook

The useEffect hook allows handling side effects such as data fetching, event listeners, and DOM manipulations.

👉 Example: Fetching Data using useEffect

import React, { useState, useEffect } from ‘react’;

function UserList() {
const [users, setUsers] = useState([]);

useEffect(() => {
fetch(“https://jsonplaceholder.typicode.com/users”)
.then(response => response.json())
.then(data => setUsers(data));
}, []);

return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}

export default UserList;

📝 How it Works:

✔ useEffect runs the callback after the component mounts.
✔ The empty dependency array [] ensures it runs only once.
✔ The fetched data updates the users state.

useEffect with Dependencies

You can specify dependencies to control when useEffect executes.

👉 Example: Re-run useEffect When State Changes

import { useState, useEffect } from “react”;

function Timer({ time }) {
useEffect(() => {
console.log(“Time updated: “, time);
}, [time]); // Runs when ‘time’ changes

return <h1>Time: {time}</h1>;
}

function App() {
const [time, setTime] = useState(0);

function updateTime() {
setTime(time + 1);
}

return (
<div>
<Timer time={time} />
<button onClick={updateTime}>Increase Time</button>
</div>
);
}

export default App;

📝 Explanation

✔ useEffect(() => {…}, [time]) → Runs whenever time updates.
✔ Console Log → Prints “Time updated: …”.
✔ Button Click → Calls setTime(time + 1), updating time.
✔Timer Component → Re-renders with new time value.

Cleaning Up Side Effects

For effects like event listeners and intervals, cleanup is necessary to avoid memory leaks.

👉 Example: Cleaning Up an Interval

import { useState, useEffect } from “react”;

function Timer() {
const [count, setCount] = useState(0);

useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);

return () => clearInterval(interval); // Cleanup when component unmounts
}, []); // Runs only once after the first render

return <h1>Timer: {count}</h1>;
}

function App() {
return (
<div>
<Timer />
</div>
);
}

export default App;

📝 Explanation

✔ useEffect with [] → Runs once when the component mounts.
✔ setInterval → Increments count every second.
✔ Cleanup function → clearInterval(interval) stops the timer when the component unmounts.

Other Important Hooks

👉 useContext - Allows sharing state between components without prop drilling.

import React, { useContext } from “react”;

const ThemeContext = React.createContext(“light”);

function ThemedComponent() {
const theme = useContext(ThemeContext);
return <h1>Theme: {theme}</h1>;
}

function App() {
return (
<ThemeContext.Provider value=”dark”>
<ThemedComponent />
</ThemeContext.Provider>
);
}

export default App;

📝 Explanation

✔ React.createContext(“light”) → Creates a context with a default value “light”.
✔ useContext(ThemeContext) → Accesses the current theme inside ThemedComponent.
✔ ThemeContext.Provider value=”dark” → Wraps ThemedComponent and provides “dark” as the theme.

👉 useRef - Maintains a reference without causing re-renders.

import React, { useRef, useEffect } from “react”;

 

function InputFocus() {

  const inputRef = useRef(null);

 

  useEffect(() => {

    inputRef.current.focus(); // Automatically focuses the input field on mount

  }, []);

 

  return <input ref={inputRef} type=”text” placeholder=”Focus on me!” />;

}

 

export default InputFocus;

📝 Explanation

✔ useRef(null) → Creates a reference to store the input element.
✔ useEffect(() => { inputRef.current.focus(); }, []) → Focuses the input once when the component mounts.
✔ ref={inputRef} → Attaches the reference to the input field.

👉 useReducer - Manages complex state logic.

import React, { useReducer } from “react”;

function reducer(state, action) {
switch (action.type) {
case “increment”:
return { count: state.count + 1 };
case “decrement”:
return { count: state.count – 1 };
default:
return state;
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => dispatch({ type: “increment” })}>Increase</button>
<button onClick={() => dispatch({ type: “decrement” })}>Decrease</button>
</div>
);
}

export default Counter;

📝 Explanation

✔ useReducer(reducer, initialState) → Manages state using a reducer function.
✔ dispatch({ type: “increment” }) → Triggers the reducer to update state.
✔ Reducer function handles actions (increment or decrement).

Conclusion

React is a powerful tool for building modern websites and applications. It is fast, efficient, and easy to use. By learning React, along with essential JavaScript concepts, you can create amazing web applications that work smoothly and look great!

Course Video in English

Chatbot