# React Skills
## Hooks
### useState
```jsx
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
```
### useEffect
```jsx
import { useState, useEffect } from 'react';
function DataFetcher({ url }) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return loading ? Loading...
: {data}
;
}
```
### useContext
```jsx
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function App() {
return (
);
}
function Child() {
const theme = useContext(ThemeContext);
return Theme: {theme}
;
}
```
### useReducer
```jsx
import { useReducer } from 'react';
const initialState = { count: 0 };
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, initialState);
return (
{state.count}
);
}
```
### Custom Hooks
```jsx
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
}
```
## Components
### Functional Component
```jsx
function Welcome({ name, age }) {
return (
Hello, {name}!
Age: {age}
);
}
```
### Props
```jsx
// Parent
// Child - receieves props
function Welcome(props) {
return Hello {props.name}
;
}
```
## Forms
### Controlled Input
```jsx
function Form() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(name);
};
return (
);
}
```