useState
Hooks basic¶
- In React, useState, as well as any other function starting with ”use”, is called a Hook.
- Hooks are special functions that are only available while React is rendering.
NoteHooks—functions starting with use—can only be called at the top level of your components or your own Hooks. You can’t call Hooks inside conditions, loops, or other nested functions. Hooks are functions, but it’s helpful to think of them as unconditional declarations about your component’s needs. You “use” React features at the top of your component similar to how you “import” modules at the top of your file.
https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e
- The useState Hook provides those two things:
- A state variable to retain the data between renders.
- A state setter function to update the variable and trigger React to render the component again.
const [index, setIndex] = useState(0);-> The [ and ] syntax here is called array destructuring and it lets you read values from an array. The array returned by useState always has exactly two items.- When you call useState, you are telling React that you want this component to remember something:
- State is isolated and private - State is local to a component instance on the screen. In other words, if you render the same component twice, each copy will have completely isolated state! Changing one of them will not affect the other.