React JS- Decoding Hooks

Nishtha Bhatia
3 min readFeb 14, 2022

What is a Hook?

As quoted by the ReactJs documentation-

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

In other words, Hooks provide an intuitive way to use the React concepts like state, refs, context and lifecycle without the need for classes. They help break complex logic into “separate concerns” while enabling the reuse of stateful logic.

We will be covering 2 hooks in detail- useState and useEffect.

The useState hook

As the name suggests, the state hook is used for state management within a component.

Syntax

const [myState, setMyState] = useState(initialValue);

useState() hook returns an array consisting of 2 elements-

  • First- The current value of state at an instant
  • Second- Function to update the state

Note: If you see an error like this.setState is not a function, you probably are storing the useState value in an object and not in an array.

Using and updating the state

Let us understand this with an example. We can handle the opening of a popup (Modal by Bootstrap) with the click of a button and hide it using state management.

const MyComponent = (props) => {
const [showModal, setShowModal] = useState(false);
const handleShow = () => setShowModal(true);
const handleClose = () => setShowModal(false);
return (
<>
<Button onClick={handleOpen}>Show popup</Button>

<Modal show={showModal} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Hello</Modal.Title>
</Modal.Header>
<Modal.Body>Have a nice day!</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleClose}>
Close
</Button>
</Modal.Footer>
</Modal>
</>
);}

On click of the button, the state value changes to true. When a state value changes, the Virtual DOM is updated first (as it is quicker). React then compares the difference between actual and virtual DOM and updates the actual DOM where necessary. In simple words, the show property of Modal becomes true and it appears. Similarly, on clicking the Close button, the showModal state is updated to false which makes the Modal disappear.

If you want to understand behind the scenes in detail, virtual dom diffing has been explained beautifully here.

The useEffect Hook

The effect hook is used to carry-out side effects in a functional component. In other words, it provides an easy way to perform certain actions in various circumstances once the component mounts. For instance, if something needs to be done when the component renders, or on a state/prop change or there is a cleanup required before unmounting- this hook is to be used. This hook can be understood as a combination of componentDidMount(), componentDidUpdate() and componentWillUnmount() from the class-based components.

Syntax

useEffect(() => {
// Perform the side effects here
});

By default, effects run after every successful render. This can however be controlled by accepting an array of dependencies like below-

useEffect(() => {
// Perform the side effects here
}, [dependencyOne, dependencyTwo]);

The code inside this effect is triggered when there is a change in the value of any of the dependencies.

Managing the React lifecycle

The effect code without dependencies is nothing but componentDidMount(). The code inside this useffect is triggered as soon as the component mounts.

As we know, we can also control the execution of code inside useEffect using dependencies. That is, execute the code when there is an update in the value of a dependency. Hence, this can play the role of componentDidUpdate(). For example, if you want to perform certain validations everytime a state changes, it can be achieved as below-

const [data, setData] = useState();useEffect(()=> {
if(data?.length > 0) {
const isValid = checkDataValid(data);
// act accordingly
} }, [data]);

Note: Either checkDataValid can be a function created inside the effect or outside the component, or else needs to be passed as a dependency to the effect (This can be a common cause for infinite re-renders).

Finally, componentWillUnmount() can be achieved using the return block inside useEffect. Any unsubscriptions or cleanup should happen here.

useEffect(() => {
return () => {
// Cleanup
};
});

These are the two most widely used hooks. There are also various useful hooks like useContext, useCallback, useMemo, etc. You can also create your custom hooks for which the convention is to prefix with ‘use’ (Example- useAction).

Finally, remember this about hooks-

  • A hook can be called from functional components.
  • A hook cannot be called conditionally but it can have conditions. That is, a hook should be there at the top level always and never within a condition/loop.
  • A hook can be called from a custom hook.

--

--