React useRef and useState Tutorial
In React, useRef and useState are two important hooks that help developers manage state and references in their applications. useRef allows us to create mutable references to DOM elements or values, while useState allows us to manage state in functional components.
useRef Hook
The useRef hook is used to create a mutable reference that can be used to store DOM elements or arbitrary values in functional components. This is useful when you need to access a DOM element or an object that persists across re-renders without causing a re-render.
To use the useRef hook, you can simply call it in your functional component and assign it to a variable. Here’s an example of using useRef to create a reference to a DOM element:
import React, { useRef } from 'react';
const MyComponent = () => {
const inputRef = useRef();
const handleClick = () => {
inputRef.current.focus();
};
return (
);
};
export default MyComponent;
useState Hook
The useState hook is used to manage state in functional components. It takes an initial value as an argument and returns an array containing the current state value and a function to update that value. When the state is updated, the component will re-render to reflect the new state.
Here’s an example of using useState to manage a counter in a functional component:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const increaseCount = () => {
setCount(count + 1);
};
return (
Count: {count}
);
};
export default MyComponent;
These are just some basic examples of how useRef and useState can be used in React applications. By using these hooks, you can effectively manage state and references in your functional components.
For more information and tutorials on React, you can visit KhaerulSite.