React Hooks have become an essential part of modern React development.
They provide a more concise and functional way to manage state and side effects in functional components.
In this quick guide, we'll explore the basic React Hooks and provide code snippets that you can easily copy and paste into your projects.
1. useState
: Managing Component State
The
useState
hook allows you to add state to your functional components.It returns an array with two elements: the current state value and a function to update it.
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> ); }
2. useEffect
: Handling Side Effects
The
useEffect
hook is used to perform side effects in your functional components. It takes a function with your side effect logic and an optional array of dependencies.
import React, { useState, useEffect } from 'react'; function DataFetching() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then((response) => response.json()) .then((data) => setData(data)); }, []); return ( <div> {data ? <p>Data: {data}</p> : <p>Loading...</p>} </div> ); }
Be wary when you use
useEffect
because if you don’t pass dependency, the useEffect callback will run indefinitely. If you pass empty array []
it will run once.3. useContext
: Accessing Context in Functional Components
The
useContext
hook allows you to access context values in functional components.import React, { useContext } from 'react'; // Create a context const MyContext = React.createContext(); function MyComponent() { const contextValue = useContext(MyContext); return ( <div> <p>Context Value: {contextValue}</p> </div> ); }
4. useRef
: Accessing DOM Elements and Storing Mutable Values
The
useRef
hook is used to access DOM elements and store mutable values that persist across renders.import React, { useRef, useEffect } from 'react'; function FocusInput() { const inputRef = useRef(null); useEffect(() => { // Focus the input element when the component mounts inputRef.current.focus(); }, []); return <input ref={inputRef} type="text" />; }
That's it! You've now got the basics of React Hooks.
These code snippets can be easily copied and pasted into your projects, allowing you to take advantage of the power and simplicity that React Hooks offer to seasoned developers.
Happy coding!