React HOOKS
React hooks, such as useState and useEffect, are used to manage state and side effects in functional components in React.
The useState hook is used to create a state variable and provide a way to update it. Here’s an example of its syntax:
const [state, setState] = useState(initialState);
In this code, state is the current value of the state variable, and setState is a function that can be used to update the state variable. The useState hook takes an initial value as an argument, which is used to set the initial value of the state variable.
Get Muhammad Noman’s stories in your inbox
Join Medium for free to get updates from this writer.
For example, we could use the useState hook to create a state variable called count with an initial value of 0:
const [count, setCount] = useState(0);
Then, we could update the value of count using the setCount function, like this:
SetCount(count+1);
The useEffect hook is used to perform side effects in a functional component. Here’s an example of its syntax:
useEffect(() => {
// Effect code goes here
}, [dependency]);
In this code, the first argument is a function that contains the side effect code. The second argument is an optional array of dependencies that the effect depends on. If any of the dependencies change, the effect will be re-run.
For example, we could use the useEffect hook to perform an API call and update the state variable when the component mounts:
useEffect(() => {
fetch(‘https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
}, []);
In this code, we’re using the fetch API to make an HTTP request to an API endpoint. When the response is received, we update a state variable called data using the setData function. We've specified an empty array as the second argument to useEffect, which means that the effect will only be run when the component mounts.
Hooks like
useStateanduseEffectare important because they allow us to write reusable and composable code in functional components. They provide a way to manage state and side effects without having to use class components or global state management libraries. This can lead to simpler and more maintainable code.






