Skip to content

Instantly share code, notes, and snippets.

View KevinVR's full-sized avatar
💻
Always Coding

Kevin Van Ryckegem KevinVR

💻
Always Coding
View GitHub Profile
// Class-based component state example
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
// Set the state
this.state = {
myValue = 'test'
function MyComponent = (props) => {
return <h1>Heading 1 Text</h1>;
};
function MyComponent = ({ headingText }) => {
return <h1>{headingText}</h1>;
};
import React, {useState} from 'react';
function MyStateComponent = ({ showHeading }) => {
// Use the useState hook from react
// Let's define the headingText in the state
const [headingText, setHeadingText] = useState('Default Heading');
// If the showHeading prop is true, we will show the heading
return showHeading ? <h1>{headingText}</h1> : null;
};
import React, {useState} from 'react';
function MyStateComponent = ({ showHeading }) => {
// useState always returns two items:
// 1. headingText - the value of our state variable
// 2. setHeadingText - the setter for our state variable
const [headingText, setHeadingText] = useState('Default Heading');
// Now, update the state depending on some condition!
if (showHeading) {
import React, {useState} from 'react';
function MyStateComponent = ({ showHeading }) => {
// Also note, the value we pass to the useState method
// will be the default/initial value!
const [headingText, setHeadingText] = useState('Default Heading');
// Our second state variable
const [paragraphText, setParagraphText] = useState('Default Paragraph');
// Now, update the state depending on some condition!
import React from 'react';
const ClickCounter = ({initialClicks}) => {
// If initialClicks is not defined, use 0 as default
const [clicks, setClicks] = useState(initialClicks || 0);
// Implement an onClick method for the button
const incrementClicks = () => {
setClicks(clicks + 1);
};
import React, {useState, useEffect} from 'react';
const UseEffectClickCounter = (props) => {
const [clicks, setClicks] = useState(initialClicks || 0);
const incrementClicks = () => {
setClicks(clicks + 1);
};
// Introduce our useEffect hook
useEffect(() => {
import React, {useState, useEffect} from 'react';
const UseEffectClickCounterMount = (props) => {
const [clicks, setClicks] = useState(initialClicks || 0);
const incrementClicks = () => {
setClicks(clicks + 1);
};
// Our 'componentDidMount' with hooks, give an empty dependency list!
useEffect(() => {
// At the root of our application, create a context
const ThemeContext = React.createContext(themes.light);
// Imagine a themes object would be available with some specific theme values such as colours
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<MyApp />
</ThemeContext.Provider>
);