Day 08: Basic Hooks

Day 08: Basic Hooks

·

2 min read

#100DaysOfCode

Day 08: Basic Hooks

useState hook is used to manage the state of a functional component. It returns an array with two values: the current state value and a setter function to update the state value. This update function re-renders the component every time it is called to render the new state value on UI.

The state is asynchronous, so in some places, it can lead to bugs like when your state is dependent on the previous state. A good rule of thumb is to always use a function is state update function if your state update depends on the previous state.

useEffect hook is a special hook that lets you run side effects in React. It runs when the component (or some of its props) changes and during the initial mount of the component.

Mount:

If you want to run the useEffect on the first render only, then pass the second argument as an empty array (it is a dependency array). The emptiness of the array means it doesn’t depend on anything.

Update:

Passing a variable in the dependency array means, the useEffect would run in the first render and also whenever that variable is changed. Not passing the second argument would run the useEffect on the first render and also on every re-render

In order to run useEffect only once or only when the variable updates, we can achieve it using the useRef hook. Which acts as a boolean variable and hides the logic using conditions.

Sometimes you need to clean up your effect from React's useEffect Hook when a component re-renders. Fortunately, this is a built-in feature of useEffect by returning a clean-up function in useEffects' effect function.

useState and useEffect are the basic hooks in React. Afterward, there are some common hooks and also custom hooks.

Article Source:

https://www.robinwieruch.de/react-useeffect-hook/

https://www.robinwieruch.de/react-hooks/

#reactjs #frontenddev #webdev #javascript #learnreact