React’s useEffect and useState Hooks
Vikrant Patel
Posted on October 8, 2023
useEffect and useState are React's most useful hooks. Let's drill down to understand the use of it.
useState
Follow through the example above:
First, you must import the destructuring useState hook from React.
Then we call the useState hook from within the counter function. The React useState returns the Value of '0' and the Counter function updates it with count and setCount.
In Short,
The React Hook useState accepts the assigned state and returns two values:
1) The current state.
2) A function that will update the state.
The fun fact is that useState Hook can be declared with any type of state variable and can be used multiple times in a single component.
useEffect:
You must be familiar with fetching data, and updating DOM and timers, these side effects in your component can be handled by useEffect Hook in React as well.
But there is a catch here,
useEffect runs on every render. In the above example when useEffect is hooked the count will change, app rerender and then triggers one after another effect.
To avoid this behavior we should always include a second parameter that accepts an array. Optionally, pass dependencies to useEffect in this array.
Let's look at some examples;
- Props or state values:
for initial rendering:
If the count variable updates, the effect will run again:
Effect Cleanup:
Some side effects require no re-use factor, such as timeouts, and event listeners.
Including the return function at the end of the useEffect will dispose of the purpose of re-rendering.
Posted on October 8, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.