Lecture Notes Of Day 11: React Hooks
Overview
Objective:
The objective of today’s lesson is to introduce students to React Hooks and how
they are used in functional components. We will cover essential hooks such as useState,
useEffect, and useContext. These hooks allow us to manage state, side effects,
and context without needing to write class-based components.
Outcome:
By the end of the lesson, students should be able to:
- Understand
the purpose and basic functionality of React hooks.
- Use
the useState hook to manage local state in functional components.
- Use
the useEffect hook to perform side effects like data fetching,
subscriptions, and manually interacting with the DOM.
- Understand
and implement the useContext hook to work with React context in functional
components.
What are React Hooks?
React hooks are functions
that let you “hook into” React state and lifecycle features from functional
components. Before React 16.8, class components were the only way to handle
state and lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
With hooks, functional components can now manage state and handle side effects
in a simpler and more concise manner.
The most commonly used
React hooks are:
1.
useState – Manages state in functional
components.
2.
useEffect – Performs side effects like
fetching data or subscribing to services.
3.
useContext – Provides a way to share
values across the component tree without having to pass props down manually at
every level.
1. useState Hook
The useState hook allows
you to add state to your functional components. It is used to declare state
variables and provides a way to update them.
Syntax:
javascript
Copy code
const [state, setState] =
useState(initialState);
- state
is the current state value.
- setState
is a function that allows you to update the state.
- initialState
is the value that the state variable will have when the component renders
for the first time.
Example:
javascript
Copy code
import React, { useState
} from 'react';
function Counter() {
// Declare a state variable
"count" initialized to 0
const [count, setCount] = useState(0);
// Update the count when the button is
clicked
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Explanation:
- In
the example above, count is a state variable initialized to 0.
- The
setCount function updates the count when the button is clicked.
- React
re-renders the component with the new count value every time setCount is
called.
2. useEffect Hook
The useEffect hook is
used to handle side effects in functional components. Side effects include
tasks like data fetching, setting up subscriptions, or manually changing the
DOM. The useEffect hook runs after the component has rendered.
Syntax:
javascript
Copy code
useEffect(() => {
// Code for side effect goes here
}, [dependencies]);
- The
function passed to useEffect is the side effect.
- The
second argument is an array of dependencies. If any value in this array
changes, the effect is run again. If no dependencies are provided (empty
array), the effect runs only once after the initial render, similar to componentDidMount.
Example: Fetching Data
javascript
Copy code
import React, { useState,
useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// Fetching data from an API
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []); // Empty dependency array ensures
this runs only once after initial render
return (
<div>
<h1>Fetched Data</h1>
{data ? <pre>{JSON.stringify(data,
null, 2)}</pre> : <p>Loading...</p>}
</div>
);
}
export default DataFetcher;
Explanation:
- The
useEffect hook is used to fetch data from an API when the component is
mounted.
- Since
the dependency array is empty, the effect runs only once, similar to how componentDidMount
works in class components.
- The
data is fetched asynchronously and then set into the state using setData.
3. useContext Hook
The useContext hook
allows you to use values from a React Context in functional components. React
Context is useful for passing data through the component tree without needing
to pass props manually at each level.
Syntax:
javascript
Copy code
const value = useContext(MyContext);
- MyContext
is the context object that was created with React.createContext().
- value
is the current value of the context.
Example: Using Context
javascript
Copy code
import React, {
useContext } from 'react';
// Create a Context for
the theme
const ThemeContext = React.createContext('light');
function ThemedComponent()
{
const theme = useContext(ThemeContext);
return <div style={{ backgroundColor: theme
=== 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff'
}}>
<h1>The current theme is {theme}</h1>
</div>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
}
export default App;
Explanation:
- We
first create a context called ThemeContext with a default value of 'light'.
- The
ThemedComponent uses the useContext hook to access the current value of
the theme (light or dark).
- The
App component provides a value for the context using ThemeContext.Provider.
This value is passed down the component tree.
Recap of Key Concepts:
1.
useState:
Used to declare and update state in functional components.
2.
useEffect: Used
for side effects, such as data fetching or setting up subscriptions, in
functional components.
3.
useContext:
Allows functional components to subscribe to context values without needing to
pass props manually.
Summary of Key Benefits
of Hooks:
- Simplicity:
Hooks allow functional components to manage state and side effects without
needing classes.
- Reusability:
Custom hooks enable reusable logic across components.
- Readability:
Hooks allow you to keep related code together, making it easier to
understand the behavior of the component.
Practice Tasks:
1.
Task 1:
Create a counter application using the useState hook. Include buttons to
increment and decrement the counter.
2.
Task 2:
Fetch and display a list of items from an API using the useEffect hook.
3.
Task 3:
Create a theme toggle button using useContext to switch between light and dark
themes in a component.
