State & useState Hook
Props Recap
So far we've worked with props
and used them to pass values from a parent
to a child
Component. This pattern of passing data down will be consistent in React as the flow of data is unidirectional
and always flows down.
We also know that the props passed down to a child are organized by React into an object where every prop becomes a key:value
pair.
Props are a great way to pass data but have the following limitations:
Props are immutable
React will ignore any attempt to reassign a prop value
Reassigning a prop value will have no effect on the Component
Intro To State
State is your application's "memory". It is data that changes as your user interacts with your app. Every time state changes, your UI (Components) should update to reflect the latest state of the application.
In React any changes to state will cause the component to rerender
. This is how the UI is updated to reflect the new state.
Working with the useState
Hook
useState
HookHooks
Hooks were introduced in React Version 16.8
. Before hooks, all state needed to be defined in a Class
component.
Hooks introduce state management to Functional components, using a simpler and more flexible API and lets you split one component into smaller functions based on what pieces are related.
They are named so because they allow function components to "hook into" React's inner workings.
The useState
hook is one of many that are built-in to React. Lots of third-party React libraries will also come with their own custom hooks.
Using useState
useState
First, import useState
:
Call the useState
hook and pass it an initial starting value:
Using State
Use the state variable to render its value:
Updating State
To update the state and trigger a rerender, the set
(setCount
) function must be used:
The above snippet will trigger a rerender, the snippet below won't:
useState
Rules and Best Practices
useState
Rules and Best PracticesRules
Here are some of the rules that govern the useState
Hook:
Never update the state value directly.
State must always be overwritten with a new value.
Always use the
set
function to update state.Don't call
useState
inside of loops, conditions, or nested functions. They must always be at the top-level of your Component. This rule also applies to all the other hooks.
Best Practices
A few best practices when assigning variable names are:
Use Array Destructuring when initializing the state variables.
Name the initial state based on what it contains.
Use the same name for the function (the second element) but precede it with
set
.Give thought as to what needs to be in state and how that state should be organized and structured.
Last updated
Was this helpful?