React Patterns — Managing State and Props
React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at how to manage states and props.
Manage States
To make our React app useful, we’ve to update states. To do this, we’ve to store an internal or shared state. We can write stateful React apps without external libraries. We just have to use them the right way.
How States Work
To set states, we can use the useState
hook.
We can use it by writing:
import React, { useState, useEffect } from "react";export default function App() {
const [msg, setMsg] = useState(""); useEffect(() => {
setMsg("foo");
}, []); return <p>{msg}</p>;
}
We have the useState
hook which returns the msg
state and the setMsg
function to set the msg
state.
useEffect
is used to set the msg
when the component loads.
The empty array in the 2nd argument indicates that the callback is run on the first load. Then we see the msg
value displayed when we render the p element.