Data handling in React refers to the management and manipulation of data within React components. This includes tasks such as fetching data from APIs, storing data locally, updating data in response to user interactions, and passing data between components.
Here are some common techniques for data handling in React:
1. State Management:
– React components can have local state managed by using the `useState` hook.
– State allows components to store and update data internally.
– State changes trigger re-renders of the component, updating the UI to reflect the new state.
– Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
2. Props:
– Data can be passed from parent components to child components using props.
– Props are immutable and are used to configure a component when it is created.
– Child components can access props passed down from their parent and use that data to render UI.
– Example:
function ParentComponent() {
const data = 'Hello from Parent';
return <ChildComponent message={data} />;
}
function ChildComponent(props) {
return <p>{props.message}</p>;
}
3. Fetching Data:
– React components can fetch data from external sources like APIs using techniques like `fetch` or libraries like Axios.
– Data fetching often occurs in lifecycle methods or useEffect hook.
– Once data is fetched, it can be stored in component state for rendering or processing.
– Example using `fetch`:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
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>}
</div>
);
}
4. Form Handling:
– React provides mechanisms for handling user input in forms.
– Input elements like text fields, checkboxes, and radio buttons can be controlled components, where their value is controlled by React state.
– Event handlers can be used to update state in response to user input.
– Example:
import React, { useState } from 'react';
function Form() {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Submitted:', inputValue);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={inputValue} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
These are some of the fundamental techniques for handling data in React applications. The choice of technique depends on factors such as the complexity of the application, data flow requirements, and personal/team preferences.