1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Manage State In A Functional Component as a react til

This commit is contained in:
jbranchaud
2019-08-17 17:43:29 -05:00
parent d40a96d534
commit 1f0fc0e9ba
2 changed files with 49 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_835 TILs and counting..._
_836 TILs and counting..._
---
@@ -557,6 +557,7 @@ _835 TILs and counting..._
- [Formik's Validation Schema As A Function](react/formiks-validation-schema-as-a-function.md)
- [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md)
- [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md)
- [Manage State In A Functional Component](react/manage-state-in-a-functional-component.md)
- [Mapping Over One Or Many Children](react/mapping-over-one-or-many-children.md)
- [Mock A Function That A Component Imports](react/mock-a-function-that-a-component-imports.md)
- [Navigate With State Via @reach/router](react/navigate-with-state-via-reach-router.md)

View File

@@ -0,0 +1,47 @@
# Manage State In A Functional Component
Before the introduction of React 16.8, you had a couple options for declaring
and managing state in your components.
The first _class_ way was to create a class component and then [add local,
component state to
it](https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class).
If you already had a functional component, you could avoid the conversion to a
class component with custom HOCs and Render Prop components or any number of
third-party libraries such as [React
PowerPlug](http://rena.to/react-powerplug/#/docs-components-state) and
[Recompose](https://github.com/acdlite/recompose).
However, projects using React 16.8+ have
[Hooks](https://reactjs.org/docs/hooks-intro.html) at their disposal. The Hooks
API's base offering is a state hook --
[`useState`](https://reactjs.org/docs/hooks-state.html).
```javascript
import React, { useState } from "react";
const Toggler = () => {
const [on, setOn] = useState(false);
const [toggleCount, setToggleCount] = useState(0);
const incrementToggleCount = setToggleCount(prev => prev + 1);
const handleToggle = () => {
setOn(prev => !prev);
incrementToggleCount();
};
return (
<React.Fragment>
<Thing on={on} />
<button onClick={handleToggle}>{on ? "ON" : "OFF"}</button>
<p>Toggle Count: {toggleCount}</p>
</React.Fragment>
);
}
```
You can manage a variety of state values in a functional component with
`useState`. The `useState` function takes the initial state value as an
argument and returns a tuple with the current state value and an _setter_
function for updating that piece of state.