Javascript Project
Javascript Project
• 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.
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
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>
);
}
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>
);
}
App.js
function App() {
return (
<div style={{ padding: '20px' }}>
<h1>React Hooks Intro</h1>
<CounterWithEffect />
<hr />
<ThemeContextExample />
</div>
);
}