DEV Community

Cover image for React Js hooks
nikhilkalariya
nikhilkalariya

Posted on

React Js hooks

1. useState Hook
Example: Counter Component

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

2. useEffect Hook
Example: Fetch Data from an API


import React, { useState, useEffect } from 'react';

const DataFetcher = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      <h1>Fetched Data</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default DataFetcher;
Enter fullscreen mode Exit fullscreen mode

3. useContext Hook
Example: Theme Context


import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

const ThemedComponent = () => {
  const theme = useContext(ThemeContext);
  return <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>Themed Component</div>;
};

const App = () => {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedComponent />
    </ThemeContext.Provider>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

4. useReducer Hook
Example: Counter with Reducer


import React, { useReducer } from 'react';

const initialState = { count: 0 };

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

const CounterWithReducer = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
};

export default CounterWithReducer;

Enter fullscreen mode Exit fullscreen mode

5. useCallback Hook
Example: Memoized Callback


import React, { useState, useCallback } from 'react';

const Button = React.memo(({ onClick }) => {
  console.log('Button rendered');
  return <button onClick={onClick}>Click me</button>;
});

const App = () => {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <Button onClick={handleClick} />
    </div>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

6. useMemo Hook
Example: Memoized Value

import React, { useState, useMemo } from 'react';

const ExpensiveCalculation = ({ count }) => {
  const calculatedValue = useMemo(() => {
    console.log('Calculating...');
    return count * 2;
  }, [count]);

  return <div>Calculated Value: {calculatedValue}</div>;
};

const App = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <ExpensiveCalculation count={count} />
    </div>
  );
};

export default App;

Enter fullscreen mode Exit fullscreen mode

7. useRef Hook
Example: Focus Input

import React, { useRef } from 'react';

const FocusInput = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

export default FocusInput;

Enter fullscreen mode Exit fullscreen mode

8. useLayoutEffect Hook
Example: Measure DOM Element

import React, { useState, useLayoutEffect, useRef } from 'react';

const MeasureComponent = () => {
  const [width, setWidth] = useState(0);
  const divRef = useRef(null);

  useLayoutEffect(() => {
    setWidth(divRef.current.offsetWidth);
  }, []);

  return (
    <div>
      <div ref={divRef} style={{ width: '50%' }}>Measured Div</div>
      <p>Width: {width}px</p>
    </div>
  );
};

export default MeasureComponent;

Enter fullscreen mode Exit fullscreen mode

9. useImperativeHandle Hook
Example: Custom Input with Forwarded Ref

import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} type="text" />;
});

const App = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

10. useDebugValue Hook
Example: Custom Hook with Debug Value

import React, { useState, useEffect, useDebugValue } from 'react';

const useCount = (initialValue) => {
  const [count, setCount] = useState(initialValue);

  useEffect(() => {
    const interval = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);

  useDebugValue(count > 5 ? 'High' : 'Low');

  return count;
};

const App = () => {
  const count = useCount(0);

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)