본문 바로가기

JavaScript

Hooks code example [React]

Hooks code examples

Hooks helps functional components. like managing state or doing work after rendering.

useState

It is the nomalist hook. This let the functional component can have variables which can change.

import React, { useState } from 'react';

const Counter = () => {
    const [value, setValue] = useState(0);
    return (
        <div>
            <p>
                current value is <b>{value}</b>.
            <p>
            <button onClick={() => setValue(value + 1)}>+1</button>
            <button onClick={() => setValue(value - 1)}>-1</button>
        <div>
    );
};

useEffect

This do some work everytime the react component rendered. It is almost like compound of 'componentDidMount' and 'componentDidUpdate'.

const Info = () => {
    const [name, setName] = useState('');
    const [nickname, setNickname] = useState('');
    useEffect(() => {
        console.log('Rendering is done');
        console.log({
            name,
            nickname
        });
    });

    const onChangeName = e => {
        setName(e.target.value);
    };

    const onChangeNickname = e => {
        setNickname(e.target.value);
    };

    return (
        (...)
    );
};

export default Info;

useContext

React ContextAPI is a way to essentially create global variables that can be passed around in aReactapp.

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('black');
const ContextSample = () => {
    const theme = useContext(ThemeContext);
    const style = {
        width: '24px',
        height: '25px',
        background: theme
    };
    return <div style={style} />;
};

export default ContextSample;

useReducer

Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happend, but don't describe how the application's state changes. -reduc.js.org

import React, { useReducer } from 'react';

function reducer(state, action) {
    switch (action.type) {
        case: 'INCREMENT':
            return { value: state.value + 1 };
        case: 'DECREMENT':
            return { value: state.value - 1 };
        default:
            return state;
    }
}

const Counter = () => {
    const [state, dispatch] = useReducer(reducer, {value: 0});  // set reducer to a state

    return (
        <div>
            <p>
               current value of count is <b>{state.value}</b>.
            </p>
            <button onClick={() => dispatch({ type: 'INCREMENT' })}> +1 </button>  // usage
            <button onClick={() => dispatch({ type: 'DECREMENT' })}> -1 </button>  // usage
        </div>
    );
};

export default Counter;

'JavaScript' 카테고리의 다른 글

Process of showing datas to client [React]  (0) 2020.07.29
Context API [React]  (0) 2020.07.27
Component keywords [React]  (0) 2020.07.27
node / express 공부기.  (0) 2020.04.25
JS 배열 정리하고 가기.  (0) 2020.04.24