React Hooks: useEffect & useContext
1. useEffect: Side Effects in React
useEffect is a React Hook used to perform side effects in function components, such
as data fetching, subscriptions, or DOM updates.
• useEffect is a Hook, so you can only call it at the top level of your
component or your own Hooks. You can’t call it inside loops or conditions. If
you need that, extract a new component and move the state into it.
• If you’re not trying to synchronize with some external system, you
probably don’t need an Effect.
2. useContext: Accessing Global Data
useContext lets you access context values directly, avoiding prop-drilling.
1. Steps to Use:
2. 1. Create a context with createContext().
3. 2. Wrap components in a Provider.
4. 3. Access context using useContext().
Let’s create a small project and see the React useEffect and useContext
Navigate to your project folder (root) and create a new project named react-hooks-
intro:
1- Set up project
2- Create 2 Javascript files for useEffect and useContext
ConterWithEffect.js
import React, { useState, useEffect } from 'react';
function CounterWithEffect() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count changed:', count);
}, [count]);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count +
1)}>Increment</button>
</div>
);
}
export default CounterWithEffect;
ThemeContextExample.js
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
function ThemeButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ backgroundColor: theme === 'dark' ? '#333' : '#ddd',
color: theme === 'dark' ? '#fff' : '#000' }}>
Current Theme: {theme}
</button>
);
}
function ThemeContextExample() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<h2>useContext Example</h2>
<ThemeButton />
<button onClick={() => setTheme(theme === 'light' ? 'dark' :
'light')}>
Toggle Theme
</button>
</ThemeContext.Provider>
);
}
export default ThemeContextExample;
3- Replace App.js and use the above components
App.js
import React from 'react';
import CounterWithEffect from './CounterWithEffect';
import ThemeContextExample from './ThemeContextExample';
function App() {
return (
<div style={{ padding: '20px' }}>
<h1>React Hooks Intro</h1>
<CounterWithEffect />
<hr />
<ThemeContextExample />
</div>
);
}
export default App;
4- Start the application
Every Time the Count is being changed , the console log (which
is effect of Count value ) will be called.
Click on Toggle Theme sends value of theme object to the
global context