React Hooks for Beginners - A Comprehensive Guide
React Hooks provides a way to use state and other React features without writing a class. They let you split one component into smaller functions based on what pieces are related (rather than forcing a split based on lifecycle methods).
The main Hooks are:
useState
- Manages local component stateuseEffect
- Performs side effects like data fetching and subscriptionsuseContext
- Access the context APIuseReducer
- Alternative touseState
for complex state logic
What are States?
State in React refers to an object that holds some information that can change over the lifetime of a component. The state is what allows you to create interactive and dynamic components.
For example, a Counter
component may have a count
state that holds the current count. When the user clicks a button, the count
is updated, and the component re-renders with the new value.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Here, count
is the state and setCount
is used to update it. When setCount
is called, and the component re-renders with the new count
value.
useState Hook
The useState
hook is used to add state to functional components. It takes the initial state as an argument and returns an array with two elements:
The current state value
A function to update it
const [state, setState] = useState(initialState);
For example:
const [count, setCount] = useState(0);
count
holds the current count (initial state is 0), and set count
is used to update the count:
setCount(count + 1); // Updates count to 1
This triggers a re-render and the new value is displayed.
You can have multiple state variables:
const [count, setCount] = useState(0);
const [name, setName] = useState('John');
useeffect Hook
The useEffect
hook allows you to perform side effects in your components.
It accepts a function that contains side effects:
useEffect(() => {
// Side effect
});
By default, it runs after every render. To run an effect once, pass an empty array as the second argument:
useEffect(() => {
// Runs once
}, []);
To run an effect whenever a value changes, pass that value in the array:
useEffect(() => {
// Runs whenever count changes
}, [count]);
It can also return a cleanup function that runs when the component unmounts:
useEffect(() => {
// ...
return () => {
// Cleanup
};
}, []);
Common uses of useEffect
include:
Data fetching
Subscribing to an event
Setting up timers
Manipulating the DOM
useContext Hook
The useContext
hook allows you to consume context in functional components.
It accepts a context object and returns its current value:
const value = useContext(MyContext);
For example:
import { ThemeContext } from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return <Button theme={theme} />
}
useReducer Hook
The useReducer
hook is an alternative to useState
.
It accepts a reducer function and initial state, and returns the current state and a dispatch function:
const [state, dispatch] = useReducer(reducer, initialArg);
A reducer function accepts the current state and an action object, and returns the new state:
const reducer = (state, action) => {
switch(action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
The dispatch function is used to trigger an action:
dispatch({type: 'increment'});
This allows you to split the logic into multiple reducer functions.
This is the end,
Hopefully, this gives you a good overview of the main React Hooks and how to use them! Let me know if you have any other questions.