Overview
Reading and practicing React 16 hooks (useState and useEffect)
- Introducing Hooks from reactjs.org
- Code Sample in codesandbox.io
Source Code
/* About React Hooks Introducing Hooks - https://reactjs.org/docs/hooks-intro.html https://reactjs.org/docs/hooks-overview.html Using the Effect Hook - https://reactjs.org/docs/hooks-effect.html */ import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; function App() { // Create a property message stored in the component state // and a funtion setMessage to update the value const [message, setMessage] = useState("no message!"); // Create a property previousMessage stored in the component state const [previousMessage, setPreviousMessage] = useState(null); // Create a property counter stored in the component state const [counter, setCounter] = useState(0); // Everytime the component update, this function is executed // Similar to componentDidMount and componentDidUpdate useEffect(() => { console.log(`[useEffect] -- GLOBAL -- message:${message}, counter:${counter}`); }); // Everytime the component update because the property message has changed, // this function is executed useEffect(() => { // Only run when message changed console.log(`[useEffect] -- message:${message}, counter:${counter}`); // We return a function that will be executed before the parent // function is executed the next time. This is used for clean up. return () => { // Run when the component unmount, // as well as before re-running the effect due to a subsequent render setPreviousMessage(message); console.log(`[useEffect Previous] -- message:${message}, counter:${counter}`); }; }, [message]); const click = () => { setMessage(` msg-${Date.now()}`); }; const onClickCounter = value => { setCounter(counter + value); }; return (); } const rootElement = document.getElementById("root"); ReactDOM.render(React useState, useEffect
Counter: {counter}
Message: {message}
previousMessage: {previousMessage}
, rootElement);
I like your post very much. I hope you to share more info about this. I found more amazing Wishes here Merry Christmas Wishes
ReplyDeleteInformative blog. Thanks for sharing.
ReplyDeleteReact JS Online training
React JS training in hyderabad
Hello Admin!
ReplyDeleteThanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this.
Oracle Training in Chennai | Certification | Online Course Training | Oracle Training in Bangalore | Certification | Online Course Training | Oracle Training in Hyderabad | Certification | Online Course Training | Oracle Training in Online | Certification | Online Course Training | Hadoop Training in Chennai | Certification | Online Course Training
wow lovely your post very much. I wish you to share more information about this.
ReplyDeleteUSA Dedicated Server I found more great Desires here