visit
Hooks allow you to use state and other React features in function components: Before the introduction of Hooks, only class-based components could have state and use other React features such as lifecycle methods. With Hooks, you can add state and other React features to function components, making them more versatile and reusable.
Hooks make your code more concise and readable: Class-based components can become long and complex, especially if you have to manage a lot of state or lifecycle methods. With Hooks, you can use simple, focused functions to handle individual pieces of state and logic, which can make your code more readable and easier to understand.
Hooks allow you to reuse stateful logic: With Hooks, you can extract stateful logic from a component and share it across multiple components, making your code more reusable and easier to maintain. This is especially useful if you have a complex component with a lot of stateful logic, and want to extract some of that logic into reusable functions.
import React, { useState } from 'react';
const myComponent = () => {
// Declare a new state variable, which we'll call "count"
// The initial value of count is 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Here is an example of how to use it:
import React, { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
// Perform some side effect, like subscribing to a data source
const subscription = someDataSource.subscribe(data => {
// Update state with the data from the subscription
setState({ data });
});
// Clean up the subscription when the component unmounts
return () => subscription.unsubscribe();
});
// Render the component
return (
<div>
{/* Use the data from the state in the render method */}
Data: {state.data}
</div>
);
}
In this example, the useEffect hook is used to set up a subscription to a data source and update the component's state with the data from the subscription. It also includes a cleanup function that will be called when the component unmounts, to ensure that the subscription is properly cleaned up and doesn't cause memory leaks.
Here is an example of how to use useContext:
import React, { useContext } from 'react';
// Create a context with a default value
const MyContext = React.createContext('defaultValue');
function MyComponent() {
// Use the useContext hook to access the value of the context
const value = useContext(MyContext);
return (
<div>
{/* Use the value from the context in the render method */}
Value from context: {value}
</div>
);
}
Here is an example of how useReducer might be used in a React component:
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
In this example, the useReducer hook is used to manage the state of a simple counter component. The hook is called with the reducer function and the initial state, and it returns the current state and a dispatch function that can be used to dispatch actions to the reducer. In this case, the component has two buttons that dispatch 'increment' and 'decrement' actions to the reducer, which updates the count in the state accordingly.
Memoization is simply an optimization technique used to increase an application's speed and efficiency. it does this by storing the results of computation and returning the cached result when the same inputs occur again.
import { useRef } from 'react';
function MyInput() {
const inputRef = useRef(null);
function handleClick() {
// Use the `current` property of the ref to access the DOM element
inputRef.current.focus();
}
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus the input</button>
</div>
);
}
In this example, the inputRef variable is created by calling useRef and passing null as the initial value for the ref. This ref is then attached to the input element by setting the ref attribute to inputRef.