useState- Hook in React Native
useState
is a React Hook that lets you add state management to your functional components in both React and React Native. It allows you to manage state variables in a simple and concise manner.
const [state, setState] = useState(initialValue);
- state: The current state value.
- setState: A function to update the state.
- initialValue: The initial value of the state.
Example: Counter App
Here’s how you can use useState
in a simple React Native app to create a counter:
Key Points
- State Initialization: You pass the initial state value (
0
in this example) touseState
. - State Update: Use the
setState
function (e.g.,setCount
) to update the state. React Native will re-render the component when the state changes. - Immutability: Avoid directly modifying the state variable; always use the setter function.