Skip to main content

React Hooks (Live Playground)

React Hooks were introduced in React 16.8 to allow functional components to manage state and use lifecycle methods, making them more powerful and flexible. In this tutorial, we'll explore the benefits of React Hooks and learn how to use the most common hooks: useState, useEffect, and useContext.

Benefits of React Hooks

React Hooks offer several benefits over traditional class components:

  • Simpler code: Functional components with hooks are generally easier to read and understand than class components.
  • Easier testing: Functional components are just plain JavaScript functions, making them easier to test and debug.
  • Reusable logic: Hooks allow you to extract and reuse stateful logic across different components, making your code more modular and maintainable.

useState

The useState hook allows functional components to manage state. It takes an initial state as its argument and returns an array with two elements: the current state and a function to update the state.

Here's an example of using useState:

JavaScript
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;

In this example, we created a Counter component that manages its state with a count variable and a button to increment the count.

Live Playground, Try it Yourself

useEffect

The useEffect hook allows functional components to perform side effects, such as fetching data, subscribing to events, or updating the DOM. It takes two arguments: a function to run the side effect and an array of dependencies to control when the effect should run.

Here's an example of using useEffect:

JavaScript
import React, { useState, useEffect } from 'react';

function Timer() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);

return () => {
clearInterval(interval);
};
}, []);

return <div>Seconds passed: {seconds}</div>;
}

export default Timer;

In this example, we created a Timer component that counts the seconds passed since it was mounted. We used the useEffect hook to start the timer when the component is mounted and to clear the timer when the component is unmounted.

Live Playground, Try it Yourself

useContext

The useContext hook allows functional components to access the React context without using a Context.Consumer. It takes a context object as its argument and returns the current context value.

Here's an example of using useContext:

JavaScript
import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

function ThemeToggleButton() {
const theme = useContext(ThemeContext);
const [isLight, setIsLight] = useState(theme === 'light');

return <button onClick={() => setIsLight(!isLight)}>Toggle theme: {isLight ? 'Light' : 'Dark'}</button>;
}

export default ThemeToggleButton;

In this example, we created a ThemeToggleButton component that toggles the theme between light and dark. We used the useContext hook to access the ThemeContext value and update the component's state accordingly.

Live Playground, Try it Yourself

Custom Hooks

Custom hooks allow you to create reusable and modular stateful logic that can be shared between components. A custom hook is just a JavaScript function whose name starts with use. It can call other hooks and return any data structure.

Here's an example of a custom hook:

JavaScript
import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const storedValue = localStorage.getItem(key);
return storedValue ? JSON.parse(storedValue) : initialValue;
});

useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);

return [value, setValue];
}

export default useLocalStorage;

In this example, we created a useLocalStorage custom hook that manages state in the browser's local storage. It takes a key and an initial value as arguments and returns an array with the current value and a function to update the value.

Conclusion

React Hooks offer several benefits over traditional class components, such as simpler code, easier testing, and reusable logic. The most common hooks, useState, useEffect, and useContext, allow functional components to manage state, perform side effects, and access context. Custom hooks enable you to create reusable and modular stateful logic that can be shared between components. Hooks have made functional components more powerful and flexible, making them the preferred choice for building modern React applications.