react-hooks
Table of Contents
useContext
In React, the useContext hook is used to access the value of a context that has been created using the createContext function. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
The useContext hook allows you to consume the value provided by a context within a functional component. Here's an example:
import React, { useContext } from 'react';
// Create a context
const MyContext = React.createContext();
// Create a component that provides the value to the context
const MyProvider = ({ children }) => {
const value = 'Hello, World!';
return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
};
// A component consuming the value from the context
const MyComponent = () => {
const contextValue = useContext(MyContext);
return <p>{contextValue}</p>;
};
// App component that uses the context
const App = () => {
return (
<MyProvider>
<MyComponent />
</MyProvider>
);
};
export default App;
In this example, we first create a context using createContext() and store it in MyContext. Then, we create a component MyProvider that wraps its children with MyContext.Provider and provides a value ('Hello, World!') to the context.
Inside the MyComponent component, we use the useContext hook to consume the value of the context. The useContext hook takes the context object as an argument and returns the current value provided by the context.
Finally, in the App component, we wrap MyComponent with MyProvider to make the context value available to MyComponent.
By using useContext, the value 'Hello, World!' from the context is accessed and rendered within the MyComponent component.
Note that the useContext hook can only be used within functional components and not in class components. It provides a straightforward way to consume the value from a context without the need for additional prop drilling.
Remember to import the necessary components and hooks from the react package when working with context and useContext.
useState
In React, useState is a built-in hook that allows you to add state to functional components. State is used to store and manage data that can change over time, such as user input, component visibility, or any other dynamic values.
The useState hook is used to declare a state variable and a function to update that variable. It returns an array with two elements: the current value of the state variable and a function to update it. Here's an example:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
};
export default MyComponent;
In this example, we use useState to declare a state variable called count and a function called setCount to update that variable. The initial value of count is set to 0 using useState(0).
Inside the component's return statement, we display the current value of count using curly braces {count}. When the "Increment" button is clicked, the incrementCount function is called, which updates the count state variable using setCount by incrementing it by 1.
When the state is updated using setCount, React re-renders the component to reflect the new state value. This allows you to create dynamic and interactive components that respond to user actions or other events.
The useState hook can be used multiple times within a component to declare different state variables. Each state variable is independent and has its own associated update function.
Overall, useState is a powerful hook in React that enables you to manage and update state in functional components, making them more dynamic and interactive.
Autocomplete
Sure! Here's an example of a React search input component that uses React-Bootstrap and includes autocomplete functionality:
import React, { useState } from 'react';
import { Form, FormControl } from 'react-bootstrap';
const SearchInput = () => {
const [searchTerm, setSearchTerm] = useState('');
const [suggestions, setSuggestions] = useState([]);
const handleInputChange = (event) => {
const newSearchTerm = event.target.value;
setSearchTerm(newSearchTerm);
// Perform autocomplete logic here
// For example, you can make an API call to fetch suggestions based on the search term
// Mocking suggestions for demonstration purposes
const mockSuggestions = ['Apple', 'Banana', 'Orange', 'Mango'];
const filteredSuggestions = mockSuggestions.filter((suggestion) =>
suggestion.toLowerCase().includes(newSearchTerm.toLowerCase())
);
setSuggestions(filteredSuggestions);
};
const handleSuggestionClick = (suggestion) => {
setSearchTerm(suggestion);
setSuggestions([]);
};
return (
<Form>
<FormControl
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleInputChange}
/>
{suggestions.length > 0 && (
<ul className="suggestions">
{suggestions.map((suggestion, index) => (
<li
key={index}
onClick={() => handleSuggestionClick(suggestion)}
>
{suggestion}
</li>
))}
</ul>
)}
</Form>
);
};
export default SearchInput;
In this example, we use the useState hook to manage the search term and suggestions. The handleInputChange function is called whenever the user types in the search input. You can perform autocomplete logic inside this function, such as making an API call to fetch suggestions based on the search term. In this example, we've mocked the suggestions for demonstration purposes.
The suggestions are displayed in an unordered list (<ul>) below the search input. When a suggestion is clicked, the handleSuggestionClick function is called to update the search term and clear the suggestions.
useEffect
In React, useEffect is a built-in hook that allows you to perform side effects in functional components. Side effects typically include tasks like data fetching, subscriptions, or manually interacting with the DOM. The useEffect hook is similar to lifecycle methods (e.g., componentDidMount, componentDidUpdate, componentWillUnmount) in class components.
The useEffect hook accepts two parameters: a callback function and an optional dependencies array.
Here's the syntax of the useEffect hook:
useEffect(() => {
// Perform side effects or cleanup tasks here
// This callback function will be executed after the component is rendered
return () => {
// Optional cleanup function
// This function will be executed when the component is unmounted or before re-rendering
};
}, [dependencies]);
The callback function passed to useEffect is executed after the component renders and re-renders. It is where you can place the code for side effects, such as making API calls, subscribing to events, or modifying the DOM.
The optional cleanup function returned from the useEffect callback is executed when the component is about to be unmounted or before re-rendering. It's used to clean up any resources or subscriptions created in the effect. This helps prevent memory leaks and ensures that the component is properly cleaned up.
The dependencies array is an optional second parameter to useEffect. It allows you to specify values that the effect depends on. When any of the values in the dependencies array change, the effect will be re-run. If the dependencies array is empty, the effect will only run once, similar to componentDidMount in class components.
By specifying dependencies in the array, you can control when the effect should re-run and avoid unnecessary re-execution of the effect if the values haven't changed.
Here's an example that demonstrates the usage of useEffect:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Perform side effects or subscribe to events
console.log('Component mounted');
return () => {
// Cleanup function
console.log('Component unmounted');
};
}, []);
return <div>My Component</div>;
}
In this example, the effect is set to run only once (empty dependencies array), similar to componentDidMount in class components. The callback function logs a message when the component is mounted and returns a cleanup function that logs a message when the component is unmounted.
Overall, the useEffect hook is a powerful tool in React that allows you to incorporate side effects and manage component lifecycle in functional components.
https://react-bootstrap.github.io/docs/getting-started/introduction